python regex match only last occurrence

守給你的承諾、 提交于 2019-12-20 01:41:08

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/20870236/python-regex-match-only-last-occurrence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!