1、正则表达式对象
regex = compile(pattern,flags = 0)
功能:生成正则表达式对象
参数:pattern 正则表达式
flags 功能标志位,扩展正则表达式的匹配
返回值:正则表达式的对象
2、re模块调用findall()
注意:正则表达式中存在子组时,返回的内容是子组匹配的对应的内容
# re模块调用findall
# findall()模块的返回值:匹配到内容的列表,如果有子组只能获取到子组对应的内容
l = re.findall(pattern, s)
print(l) # ['Alex:1994', 'Sunny:1996']
# 如果正则表达式有两个子组,匹配到的每一处内容返回的子组内容构成元组
l1 = re.findall(prttern1, s)
print(l1) # [('Alex', '1994'), ('Sunny', '1996')]
3、正则表达式对象调用findall()
# compile对象(正则表达式对象)调用findall(pattern,pos,endpos)
regex = re.compile(pattern)
regex.findall(s)
4、总结
re模块直接调用findall()方法的底层实现:调用findall方法,返回值为_compile先生成一个正则表达式对象,然后调用findall(string)
def findall(pattern, string, flags=0):
return _compile(pattern, flags).findall(string)
def findall(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> list[Any]: ...
区别:先生成正则表达式对象,再调用findall,参数更多,
findall(self, string: AnyStr, pos: int = ..., endpos: int = ...)
5、扩展
以下方法的使用,与上述情况一致,可以使用re直接调用或者先生成正则表达式对象,再调用,区别也一样,参数更丰富
split
sub
subn
finditer
fullmatch
match
search
以上方法的使用,见正则表达式的使用(二)
https://editor.youkuaiyun.com/md/?articleId=130254677