Grouping and OR in regex
python, regex
Solution
The only way would be the branch reset feature using Python's regex module.
>>> import regex
>>> m = regex.search(r'(?|a+(\sb)|b+(\sa))', 'b a')
>>> m.group()
'b a'
>>> m.group(1)
' a'
>>> m = regex.search(r'(?|a+(\sb)|b+(\sa))', 'a b')
>>> m.group()
'a b'
>>> m.group(1)
' b'
As stated in the documentation:
Group numbers will be reused across different branches of a branch reset... eg. `(?|(first)|(second))` has only group `1`.
The conditional regular expression considered a duplicate subpattern group share the same number in any subpatterns in `( .. )` in such a group. If the condition is satisfied, the first pattern is used; otherwise the second pattern is used.
Problem
``` >>> import re >>> p='a+(\sb)|b+(\sa)' >>> m=re.search(p, 'b a') >>> m.group() 'b a' >>> m.group(1) >>> >>> m=re.search(p, 'a b') >>> m.group() 'a b' ``` I use `|` as OR, and make one group on both sides of `|`. I wonder why the group isn't captured in `m.group(1)`? Thanks. Edit: I want to match one regex (with one group) in a text. I also want to match another regex (with one group) in the text. Whichever regrex matches first in the text, I will choose the group of that match (i.e. if I were matching each regex separately, I would pick out group 1 of the matched regex). I thought OR the two regrex's would work. But it doesn't, what would you do if you were me?