python regex只匹配最后一次 [英] python regex match only last occurrence

查看:166
本文介绍了python regex只匹配最后一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 >>> re.findall('(\(\w +,\d + \)(?:,)?)+','(a,b),(c,d),(e,f)')
['(e,f)']

我想要得到其他项目好吧



帮助将真正的appriciated

解决方案

删除 + ;您的模式匹配所有事件,但该组只能捕获一次,您不能以这种方式重复捕获组:

 >>> import re 
>>> re.findall('(\(\w +,\w + \),?)+','(a,b),(c,d),(e,f)')
[ '(e,f)']
>>> re.findall('\(\w +,\w + \),?','(a,b),(c,d),(e,f)')
['(a ,b),','(c,d),','(e,f)']

在那里我用 \w 替换 \d 来演示,并删除冗余非捕获组周围逗号。最外面的捕获组也是多余的;没有它, re.findall()返回整个匹配的表达式。


I'm experiencing some problems implementing a regular expression for a repeating string pattern.

>>> re.findall('(\(\w+,\d+\)(?:,)?)+', '(a,b),(c,d),(e,f)')
['(e,f)']

I would like ro get the other items as well

Help would be really appriciated

解决方案

Remove the +; your pattern matches all occurrences, but the group can only capture one occurrence, you cannot repeat a capturing group that way:

>>> import re
>>> re.findall('(\(\w+,\w+\),?)+', '(a,b),(c,d),(e,f)')
['(e,f)']
>>> re.findall('\(\w+,\w+\),?', '(a,b),(c,d),(e,f)')
['(a,b),', '(c,d),', '(e,f)']

where I replaced the \d with \w to demonstrate, and removed the redundant non-capturing group around the comma. The outermost capturing group is also redundant; without it, re.findall() returns the whole matched expression.

这篇关于python regex只匹配最后一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆