2

Say I have the following regular expression and searches

e = r"(?P<int>\d+)|(?P<alpha_num>\w)"
num = re.search(e, "123z")
letter = re.search(e, "z123")

I know that num.group("int") gives 123 and num.group("alpha_num") gives None. Similarly letter.group("int") give None and letter.group("alpha_num") give z

However, what I want is a way to get the "named category" for an arbitrary match. So if I have an arbitrary match, say new_match, I could call new_match.named_category() and it would return "int" or "alpha_num" depending on how it matched.

Does any such command exist or do I have to create my own?

Thanks!

1 Answer 1

1

For the specific example in your question, you can use lastgroup:

>>> import re
>>> e = r"(?P<int>\d+)|(?P<alpha_num>\w)"
>>> num = re.search(e, "123z")
>>> letter = re.search(e, "z123")
>>> num.lastgroup
'int'
>>> letter.lastgroup
'alpha_num'
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer, forgot about lastgroup.

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.