Skip to content Skip to sidebar Skip to footer

How To Search String Members Of A List In Another String In Python 2

I have a string, let's say an email From field: str1 = 'Name ' (or perhaps with another format, the thing is that inside of str an email address is

Solution 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([])

Solution 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.

Solution 3:

I don't know if this is pythonic:

return str1.split('<')[1].split('>')[0] in lst

Post a Comment for "How To Search String Members Of A List In Another String In Python 2"