Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to match list elements individually against AND / ALL / multiple patterns in Python – list(), re.match()?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading