Sam Rohn
Sam Rohn

Reputation: 369

regex: retrieve which pattern matched

I am trying to infer the pattern from a list of email to see if the email id follows firstname.lastname or lastname.firstname pattern. I can match email by using an 'or' with the possible patterns like below

re.match("|".join([regex_pat1, regex_pat2]), email)

Once I get a match, how do I know which regex pattern string from list matched the target email?

edit: example

import re
email = "[email protected]"

patt = ["[email protected]", "[email protected]"]

re.match("|".join(patt), email)

This gives me a match object <_sre.SRE_Match object; span=(0, 30), match='[email protected]'>

What I want to know is which one of my pattern from my 'patt' list matched

Upvotes: 1

Views: 237

Answers (2)

KC.
KC.

Reputation: 3107

Honestly your question confused me, because if you match successfully that the pattern should equal to email. And you can check if it follows firstname.lastname or lastname.firstname pattern through print(email in patt) since you have email and patt.

In regex, . will matche all character that except for line terminators(\n) . If you only want to match the . then add a backslash \. or [.]#(not recommended)

Upvotes: 1

1010
1010

Reputation: 1848

You can use parentheses to enclose your patterns and identify your match with a matching group as in

patt = ["(sam\.rohn@gmail\.com)", "(rohn\.sam@gmail\.com)"]

see here

Upvotes: 1

Related Questions