I have a list and I want only the list elements that match ALL patterns in the regex. I can't seem to figure this out, I'm new to this and thank you for your help.
The resulting print/list should only be one instance of 'panic'
import re
green = ['.a...', 'p....', '...i.']
wordlist = ['names', 'panic', 'again', '.a...']
for value in wordlist:
for pattern in green:
#print(value, pattern)
if re.match(pattern, value):
print(value)
#=>
names
panic
panic
panic
again
.a...
CodePudding user response:
Here's a small modification of your code:
import re
green = ['.a...', 'p....', '...i.']
wordlist = ['names', 'panic', 'again', '.a...']
for value in wordlist:
for pattern in green:
if not re.match(pattern, value):
break
else:
print(value)
See this question for the for/else
construct.
Different approach
hits = (v for v in wordlist if all(re.match(pattern, v) for pattern in green))
for h in hits:
print(h)
CodePudding user response:
I would suggest to use function all
import re
patterns = ("regex1", "regex2", "regex3")
wordlist = ("word1", "word2", "word3")
for word in wordlist:
if all(re.match(pattern, word) for pattern in patterns):
print(word)