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 |
.
jsbueno
source share