前情回顾
什么是正则表达式
元字符
正则表达式的转义,贪婪,分组
正则表达式的匹配原则
re模块的使用
+++++++++++++++++++++++++++++++++++++++++++++
match对象属性
pos
endpos
re
string
lastgroup
lastindex
例:
import re
pattern = r'(?P<dog>ab)cd(?P<pig>ef)'
regex = re.compile(pattern)
match_obj =regex.search('abcdefghij',pos=0,endpos=6)
print(match_obj.pos) #
print(match_obj.endpos)
# pos 和 endpos 分别表示目标字符串的起始位置
# 可以指定起始位置
print(match_obj.re) # 返回正则表达式
print(match_obj.string) # 返回目标字符串
print(match_obj.lastgroup) # 返回最后一个分组名称
print(match_obj.lastindex) # 返回最后一个分组是第几组
print(match_obj.start()) # 匹配内容的开始位置
print(match_obj.end()) # 匹配内容的结束位置
print(match_obj.span()) # 匹陪内容的起止位置
group()
功能: 获取match对象对应的内容
参数: 默认为0,表示获取整个正则匹配的内容
如果为序列号或者子组名则获取某个子组匹配的对应内容
返回值:返回得到的字符串
print(match_obj.group()) # 获取整个match对象
print(match_obj.group(2)) # 通过序列号获取匹配到的内容
print(match_obj.group('pig')) # 通过子组名称获取匹配到的内容
print(match_obj.groupdict()) # 获取捕获组字典
print(match_obj.groups) # 获取每一个子组匹配到的内容
flags 参数的使用
re.compile re.findall re.search re.match
re.findter re.fullmatch re.sub re.subn re.split
作用: 辅助正则表达式,丰富匹配结果
I = IGNORECASE 匹配时忽略字母大小写
S = DOTALL 作用于元字符.使其可以匹配换行符
M = MULITLINE 作用于 ^ $,使其可以匹配每一行开头结尾 的位置
X = VERBOSE 可以结合正则添加注释
* 注意:当时用多个标志位时用按位或连接
例:
flags = re.X | re.I