Python regex: get named group name

I have something like this:

$ pattern = re.compile('(?P<group1>AAA|BBB|CCC)|(?P<group2>DDD|EEE|FFF)')

If I am looking for a matching object, I am not interested in what 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 this is group2 by simply repeating over the dict, but it seems slow if I have many matches to check. Is there a more direct way to get the name of the group? (Python 2.7)

+4
source share
1 answer

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'
+6
source

Source: https://habr.com/ru/post/1539817/


All Articles