regexes: How to access multiple matches of a group?


Question

I am putting together a fairly complex regular expression. One part of the expression matches strings such as '+a', '-57' etc. A + or a - followed by any number of letters or numbers. I want to match 0 or more strings matching this pattern.

This is the expression I came up with:

([\+-][a-zA-Z0-9]+)*

If I were to search the string '-56+a' using this pattern I would expect to get two matches:

+a and -56

However, I only get the last match returned:

>>> m = re.match("([\+-][a-zA-Z0-9]+)*", '-56+a')
>>> m.groups()
('+a',)

Looking at the python docs I see that:

If a group matches multiple times, only the last match is accessible:

>>> m = re.match(r"(..)+", "a1b2c3")  # Matches 3 times.
>>> m.group(1)                        # Returns only the last match.
'c3'

So, my question is: how do you access multiple group matches?

1
60
2/19/2019 7:09:31 PM

Accepted Answer

Drop the * from your regex (so it matches exactly one instance of your pattern). Then use either re.findall(...) or re.finditer (see here) to return all matches.

Update:

It sounds like you're essentially building a recursive descent parser. For relatively simple parsing tasks, it is quite common and entirely reasonable to do that by hand. If you're interested in a library solution (in case your parsing task may become more complicated later on, for example), have a look at pyparsing.

57
2/20/2011 11:28:49 PM

The regex module fixes this, by adding a .captures method:

>>> m = regex.match(r"(..)+", "a1b2c3")
>>> m.captures(1)
['a1', 'b2', 'c3']

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon