6

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)

1 Answer 1

11

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Well, I feel a bit sheepish about my question now, the answer looks just to easy x) Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.