简体   繁体   中英

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 = "sam.rohn@gmail.com"

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

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

This gives me a match object <_sre.SRE_Match object; span=(0, 30), match='sam.rohn@gmail.com'>

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM