Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If any strings in a list match regex

Tags:

I need to check if any of the strings in a list match a regex. If any do, I want to continue. The way I've always done it in the past is using list comprehension with something like:

r = re.compile('.*search.*') if [line for line in output if r.match(line)]:   do_stuff() 

Which I now realize is pretty inefficient. If the very first item in the list matches, we can skip all the rest of the comparisons and move on. I could improve this with:

r = re.compile('.*search.*') for line in output:   if r.match(line):     do_stuff()     break 

But I'm wondering if there's a more pythonic way to do this.

like image 241
ewok Avatar asked Jun 22 '16 16:06

ewok


People also ask

How do you check if a string matches a regex?

Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).


2 Answers

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.

like image 65
MrAlexBailey Avatar answered Oct 10 '22 08:10

MrAlexBailey


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 (either None or a re.Match object)
  • Applies the truth value of match as part of the any expression (None -> False, Match -> True)
  • If match is None, then the any search loop continues
  • If match has captured a group, then we exit the any expression which is considered True and the match variable can be used within the condition's body
like image 40
Xavier Guihot Avatar answered Oct 10 '22 06:10

Xavier Guihot