Match string with multiple regexes using Python

Is there a way to see if a string contains words that match a set of regular expression patterns? If I have [regex1, regex2, regex3] and I want to see if the line matches any of them, how can I do this? Right now, I'm using re.findall(regex1, line) , but it only matches 1 regex at a time.

+7
source share
3 answers

You can use the built-in functions any (or all if all regular expressions must match) and the Generator expression to loop through all the regex objects.

any (regex.match(line) for regex in [regex1, regex2, regex3])

(or any(re.match(regex_str, line) for regex in [regex_str1, regex_str2, regex_str2]) if the regular expressions are not precompiled regular objects, of course)

Although this will be vague compared to combining your regular expressions into a single expression - if this code is time or processor critical, try instead creating a single regular expression that covers all your needs using a special regular expression | operator to separate the original expressions. An easy way to combine all regular expressions is to use the string join operator:

re.match("|".join([regex_str1, regex_str2, regex_str2]) , line)

Although combining regular expressions in this form can lead to incorrect expressions if the original ones already use the | .

+20
source

Try this new regex: (regex1) | (regex2) | (regex3). This will match a string with any of the three regular expressions.

+1
source

You combine regular expression elements and do a search.

 regexList = [regex1, regex2, regex3] line = 'line of data' gotMatch = False for regex in regexList: s = re.search(regex,line) if s: gotMatch = True break if gotMatch: doSomething() 
+1
source

All Articles