3

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

Lucidnonsense
  • 1,195
  • 3
  • 13
  • 35
  • I get `('C',)`, not `('A',)`. Per [this demo](https://regex101.com/r/yY5sT1/1) *"A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data"* – jonrsharpe May 07 '15 at 09:44
  • Sorry, yes I get C as well. Question edited – Lucidnonsense May 07 '15 at 09:50

1 Answers1

5

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']
poke
  • 369,085
  • 72
  • 557
  • 602