I have a regex defined as such, it’s two regular expressions separated by an OR – I want to find lines from a text file that match either of these regexes…
my_regex = re.compile(r'^s+V.*CORE.*?: (S+)|^s+NP._VDDC_V: (S+)')
# ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
# regex1 regex2
# now we do the search...
my_match = my_regex.search(line)
the lines I am searching will match regex1 or regex2 or neither (but never both!). The value I’m interested in is the S+
enclosed in grouping parenthesis in both regexes.
When the line matches regex1, I get what I want by looking at my_match.groups(1)
. But when the line matches regex2, I have to go get what I want from my_match.groups(2)
.
Is there a super slick pythonic way to say “give me the group from the thing that actually matched” ?
I know that I can do something like dig through the match object, looking at my_match.regs
… the group that didn’t match will be .regs[n] = (-1,-1)
so and the one that did match will have actual offsets … I could look at them in order and find the one that is NOT (-1,-1)
… but it seems like there’s always some much more elegant way to do this that I’m just not aware of.
2