If any strings in a list match regex
Given that I am not allowed to comment yet, I wanted to provide a small correction to MrAlexBailey's answer, and also answer nat5142's question. Correct form would be:
r = re.compile('.*search.*')
if any(r.match(line) for line in output):
do_stuff()
If you desire to find the matched string, you would do:
lines_to_log = [line for line in output if r.match(line)]
In addition, if you want to find all lines that match any compiled regular expression in a list of compiled regular expressions r=[r1,r2,...,rn], you can use:
lines_to_log = [line for line in output if any(reg_ex.match(line) for reg_ex in r)]
Starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), we can also capture a witness of an any
expression when a match is found and directly use it:
# pattern = re.compile('.*search.*')
# items = ['hello', 'searched', 'world', 'still', 'searching']
if any((match := pattern.match(x)) for x in items):
print(match.group(0))
# 'searched'
For each item, this:
- Applies the regex search (
pattern.match(x)
) - Assigns the result to a
match
variable (eitherNone
or are.Match
object) - Applies the truth value of
match
as part of the any expression (None
->False
,Match
->True
) - If
match
isNone
, then theany
search loop continues - If
match
has captured a group, then we exit theany
expression which is consideredTrue
and thematch
variable can be used within the condition's body
You can use the builtin any()
:
r = re.compile('.*search.*')
if any(r.match(line) for line in output):
do_stuff()
Passing in the lazy generator to any()
will allow it to exit on the first match without having to check any farther into the iterable.