I have something like this:
$ pattern = re.compile('(?P<group1>AAA|BBB|CCC)|(?P<group2>DDD|EEE|FFF)')
If I'm looking at a match object I'm not really interested which specific text was matched, I just want to know if it was group1 or group2
groupdict() gives me something like this:
$ match.groupdict()
$ {'group1': None, 'group2': 'DDD'}
Now, of course, I could find out that it's group2 by just iterating over the dict, but that seems slow if I have a lot of matches to check. Is there a more direct way to get the group name? (Python 2.7)
Maybe lastgroup
?
>>> pattern = re.compile('(?P<group1>AAA|BBB|CCC)|(?P<group2>DDD|EEE|FFF)')
>>> m = pattern.search("AAA")
>>> m.lastgroup
'group1'
>>> m = pattern.search("DDD")
>>> m.lastgroup
'group2'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With