Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Not in a List - Python

Is there a way that I could include into my expression the ability for me to check if the item isn't in a list.

I have the Situation where I have a list of words:

listA = ["Abc","Def","etc"]

What I want to do is to perform the match where it matched the Regular Expression, but the match didn't contain any of the words given in the list?

I can do this without regular expressions, but wondering if there was an inbuilt way in Python to do this.

For example:

names = ["David","John","Bob"]
x = "From [email protected] Sat Jan 5 09:14:16 2008"

y = re.findall([NOT in Names]+'\S+@\S+',x)

The expected output will should be an empty list. (because it contains John) If the email above was [email protected] then I would like the output to be

['[email protected]']
like image 218
KingJohnno Avatar asked Aug 26 '26 12:08

KingJohnno


1 Answers

You could do it like this:

names = ["David","John","Bob"]
x = """From [email protected] Sat Jan 5 09:14:16 2008
       From [email protected] Sat Jan 5 09:14:16 2008"""
y = [m[0] for m in re.findall('((\S+)@\S+)',x) if m[1] not in names]
-> ['[email protected]', '[email protected]']
like image 69
isedev Avatar answered Aug 28 '26 03:08

isedev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!