1

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...
mtncodes
  • 15
  • 6

2 Answers2

4

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)
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • 1
    Thank you! I see now that I can use inverse logic to create the all() boolean outcome. Thanks for the second approach as well, that is what I was trying to use originally. – mtncodes Feb 17 '22 at 16:22
0

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)
Marek Gancarz
  • 206
  • 3
  • 5