Stev0
Stev0

Reputation: 605

List containing strings and traditional regular expressions

I'm writing a script to check the contents of files in a directory. What I've got so far is a list with various strings, and would also like to include a traditional regular expression in the search. Here's what I have so far:

regex = [ "STRING1", "STRING2", "STRING3", (?:<my regex here>)]
pattern = re.compile(regex)

I'm getting various errors and have tried trouble shooting it a bit, prepending r' to the regex, using .join() in the compile function, clearly I'm doing something wrong. The code executes properly but does not find matches when it should, so obviously my regex is being compiled incorrectly. So what is the correct way to make a list of the regexes I want to use, and then iterate over that list in my search?

Upvotes: 1

Views: 109

Answers (1)

SamGamgee
SamGamgee

Reputation: 564

Are you trying to do something like this?:

import re

# Pre-compile the patterns
regexes = [ re.compile(p) for p in [ 'this',
                                     'that',
                                     ]
            ]
text = 'Does this text match the pattern?'

for regex in regexes:
    print 'Looking for "%s" in "%s" ->' % (regex.pattern, text),

    if regex.search(text):
        print 'found a match!'
    else:
        print 'no match'

It was taken from PyMOTW.

Upvotes: 2

Related Questions