DSUR
DSUR

Reputation: 43

Pulling Out a Part of a Regular Expression (Python)

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!

Upvotes: 2

Views: 33

Answers (1)

ekhumoro
ekhumoro

Reputation: 120608

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'

Upvotes: 1

Related Questions