简体   繁体   中英

python regex match only last occurrence

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM