Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex: get name of named group

Tags:

python

regex

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)

like image 382
Eulelie Avatar asked May 08 '14 21:05

Eulelie


1 Answers

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'
like image 68
DSM Avatar answered Sep 20 '22 10:09

DSM