正则表达式的使用

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值