Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex with repeating groups

Tags:

python

regex

I've been trying to match a phrase between hyphens. I realise that I can easily just split on the hyphen and get out the phrases but my equivalent regex for this is not working as expected and I want to understand why:

([^-,]+(?:(?: - )|$))+

[^-,]+ is just my definition of a phrase

(?: - ) is just the non capturing space delimited hyphen

so (?:(?: - )|$)is capturing a hyphen or end of line

Finally, the whole thing surrounded in parentheses with a + quantifier matches more than one.

What I get if I perform regex.match("A - B - C").groups() is ('C',)

I've also tried the much simpler regex ([^,-]+)+ with similar results

I'm using re.match because I wanted to use pandas.Series.str.extract to apply this to a very long list.

To reiterate: I'm now using an easy split on a hyphen but why isn't this regex returning multiple groups?

Thanks

like image 912
Lucidnonsense Avatar asked Jun 22 '26 18:06

Lucidnonsense


1 Answers

Regular expression capturing groups are “named” statically by their appearance in the expression. Each capturing group gets its own number, and matches are assigned to that group regardless of how often a single group captures something.

If a group captured something before and later does again, the later result overwrites what was captured before. There is no way to collect all a group’s captures values using a normal matching.

If you want to find multiple values, you will need to match only a single group and repeat matching on the remainder of the string. This is commonly done by re.findall or re.finditer:

>>> re.findall('\s*([^-,]+?)\s*', 'A - B - C')
['A', 'B', 'C']
like image 163
poke Avatar answered Jun 25 '26 08:06

poke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!