正则表达式(五)------ 匹配模式

1.不区分大小写模式

>>> re.search(r"(?i)the","THe")!=None           #指定方式一,括号并不影响捕获分组的编号
True
>>> re.compile(r"the",re.I).search("THe")!=None #python中也可以这样指定
True
>>> re.search(r"the","THe",re.I)!=None
True


2.单行模式-------DOTALL模式---------在该模式下点号可以匹配换行符

>>> re.search(r"^.*abcde$","\nabcde")!=None     #默认模式下点号不能匹配\n
False
>>> re.search(r"(?s)^.*abcde$","\nabcde")!=None  #单行模式
True
>>> re.search(r"^.*abcde$","\nabcde",re.S)!=None  #python中还可以这样指定单行模式
True
>>> re.search(r"^.*abcde$","\nabcde",re.DOTALL)!=None
True


3.多行模式------决定$和^的匹配类型

>>> s="1 line\nno digit\n3 line"   #字符串s中有多行文本
>>> print(s)
1 line
no digit
3 line
在普通模式下,$和^只能匹配整个字符串的结束和开始位置:

>>> re.findall(r"^\d",s)
['1']
>>> re.findall(r"\w+$",s)
['line']

在多行模式下,^和$可以匹配每一行的开始和结束位置:

>>> re.findall(r"(?m)^\d",s)
['1', '3']
>>> re.findall(r"(?m)\w+$",s)
['line', 'digit', 'line']

在python中也可以用下面方式来标识多行模式

>>> re.findall(r"\w+$",s,re.M)
['line', 'digit', 'line']
>>> re.findall(r"\w+$",s,re.MULTILINE)
['line', 'digit', 'line']

4.注释模式

当这则表达式太长太复杂变得难以维护时,需要使用注释:

>>> regex1=r"""
(?x)	#mode
\w+$    #ends with words
"""
>>> re.findall(regex1,s)
['line']

5.多种模式同时使用

>>> regex1=r"""
(?mx)	#multiple line and extended mode
\w+$    #ends with words
"""
>>> re.findall(regex1,s)
['line', 'digit', 'line']



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值