8、正则表达式-re方法的属性

  • 编译标志-flags

  DOTALL,S:使.匹配包括换行在内的所有字符

  IGNORECASE,I:使匹配对大小写不敏感

  LOCAL,L:本地化识别(local-aware)匹配.法语等

  MULTILINE,M:多行匹配,影响^和$

>>> s = '''
hello python
python hello
hello python hello
python hello py
'''
>>> re.findall(r'^hello',s)           
[]
>>> re.findall(r'^hello',s,re.M)       #当字符串 为多行时,需要加M来让正则匹配
后面的字符
['hello', 'hello']
>>> s
' hello python python hello hello python hello python hello py '

  VERBOSE,X:能够使用REs的verbose状态,使之被组织的更加清晰易懂

>>> tel = r'''
d{3,4}
-?
d{8}
'''
>>> re.findall(tel,'010-12345678')
[]
>>> re.findall(tel,'010-12345678',re.X)       #当正则表达式为多行时,需要加入X属性来使正则表达式清晰易懂
['010-12345678']
>>> tel
'
\d{3,4}
-?
\d{8}
'

  分组:'('和')',可以把相关的数据化为一个整体,在这个整体中可以做其他操作,比如|(或),findall会优先返回分组中的数据

>>> email = r'w{3,8}@w+(.com|.cn)'
>>> re.findall(email,'test@hiker.com')
['.com']
一个初识C++的小白
原文地址:https://www.cnblogs.com/Real-m/p/13627826.html