问题
I have a string, let's say an email From field:
str1 = "Name <emailaddress@example.com>"
(or perhaps with another format, the thing is that inside of str an email address is found...)
And I have a list of addresses:
lst = ["email1@example.com", "email2@yahoo.com", "email3@mail.com", "emailaddress@example.com"]
What is the most pythonic way to search if the part of str with the email address is one of the members on lst ?
In the example, the email part of str1 is part of lst, but for:
str2 = "Another email emailexample@domain.com"
it is not...
Also,
str3 = "Example email1@example.com"
would match because email1@example.com is in the list, no matter there's no '<' '>' surrounding the email addres...
回答1:
from http://love-python.blogspot.com/2008/04/python-code-to-scrape-email-address.html
>>> email_pattern = re.compile("[-a-zA-Z0-9._]+@[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+")
>>> str = "Name <emailaddress@example.com>"
>>> str2 = "Another email emailexample@domain.com"
>>> lst = ["email1@example.com", "email2@yahoo.com", "email3@mail.com", "emailaddress@example.com"]
>>> import re
>>> set(re.findall(email_pattern, str)).intersection(lst)
set(['emailaddress@example.com'])
>>> set(re.findall(email_pattern, str2)).intersection(lst)
set([])
回答2:
Usually regex are not considered pythonic, but this seems a task made exactly for them.
So I would use them, extract the email adress and check if it's in
the list:
>>> re.search(r'<(.*)>', "Name <emailaddress@example.com>").group(1) in lst
True
"pythonic" isn't a word to throw there that will solve any problem, one should consider all the available options and choose the best one.
Edit: If the format of your field isn't standard, no problem: you just need a better regex that will match the email. (I'm sure there are a ton of examples out there, I'm not going to google it for you).
But that doesn't mean that you shouldn't use regex for this kind of task.
回答3:
I don't know if this is pythonic:
return str1.split('<')[1].split('>')[0] in lst
来源:https://stackoverflow.com/questions/9711963/how-to-search-string-members-of-a-list-in-another-string-in-python-2