0
点赞
收藏
分享

微信扫一扫

python - re.findall() 方法 正则表达式中带括号的匹配规则


python - re.findall() 方法正则表达式中带括号的匹配规则

python 正则括号的使用踩坑及注意事项
[a-z]+\d+
([a-z]+)(\d+)
(([a-z]+)(\d+))
以上三个表达式在 vscode 中查询结果一样,但是 python 中返回的结果是三种不同数据类型,使用是需要注意!!!

配规则:
1.正则中没有括号时,返回的是 list,list的元素是 str ;
2.正则中有括号时,返回的是 list,list的元素是 tuple ,tuple 中的各项对应的是括号中的匹配结果;

如何让带有括号的表达式返回正确结果呢?
答案是在最外层在嵌套一层括号,获取元组中的第一项。

实例:获得 aa11 这种结构的数据

def test():
txt = 'aa11bb22cc33'
rst = re.findall(r'[a-z]+\d+',txt)
print('type=%s result=%s'%(type(rst),rst))
rst = re.findall(r'([a-z]+)(\d+)',txt)
print('type=%s result=%s'%(type(rst),rst))
rst = re.findall(r'(([a-z]+)(\d+))',txt)
print('type=%s result=%s'%(type(rst),rst))
passtest()
运行结果:
type=<class 'list'> result=['aa11', 'bb22', 'cc33']
type=<class 'list'> result=[('aa', '11'), ('bb', '22'), ('cc', '33')]
type=<class 'list'> result=[('aa11', 'aa', '11'), ('bb22', 'bb', '22'), ('cc33', 'cc', '33')]


举报

相关推荐

0 条评论