Last updated: Apr 9, 2024
Reading timeยท3 min
To check if any element in a list matches a regex:
re.match
method to check if each string in the list matches the
regex.any()
function.import re prog = re.compile(r'[a-z]+') my_list = ['!', '?', 'abc'] if any((match := prog.match(item)) for item in my_list): print('At least one list item matches regex') print(match.group(0)) # ๐๏ธ 'abc' else: print('No list items match regex') print(prog.match('abc').group(0)) # ๐๏ธ 'abc'
Note that the re.match() method only matches a regular expression at the beginning of a string.
The re.search
method checks for a match anywhere in the string.
import re prog = re.compile(r'[a-z]+') my_list = ['!', '?', '???abc???'] # ๐๏ธ using re.search() instead if any((match := prog.search(item)) for item in my_list): print('At least one list item matches regex') print(match.group(0)) # ๐๏ธ 'abc' else: print('no list items match regex') print(prog.search('???abc???').group(0)) # ๐๏ธ 'abc'
We used the re.compile()
method to compile a regular expression pattern into an object, which can be used
for matching using its match()
or search()
methods.
import re prog = re.compile(r'[a-z]+') print(prog) # ๐๏ธ re.compile('[a-z]+')
This is more efficient than using re.match
or re.search
directly because it
saves and reuses the regular expression object.
The re.search method looks for the first location in the string where the provided regular expression produces a match.
import re prog = re.compile(r'[a-z]+') my_list = ['!', '?', '???abc???'] if any((match := prog.search(item)) for item in my_list): print('At least one list item matches regex') print(match.group(0)) # ๐๏ธ 'abc' else: print('no list items match regex') print(prog.search('???abc???').group(0)) # ๐๏ธ 'abc'
re.search()
method finds a match, it will return a match
object, otherwise None
is returned.We used a generator expression to iterate over the list.
The :=
syntax is called
assignment expressions
in Python.
if any((match := prog.search(item)) for item in my_list): print('At least one list item matches regex') print(match.group(0)) # ๐๏ธ 'abc'
Assignment expressions allow us to assign to variables within an expression
using the NAME := expression
syntax.
The any function
takes an iterable as an argument and returns True
if any element in the
iterable is truthy.
The re.search
and re.match
methods return a match
object if the string
matches the regular expression, otherwise, they return None
.
If any element in the list matches the regex
, the any()
method returns
True
and the if
block runs.
If the iterable is empty or none of the elements in the iterable are truthy, the
any
function returns False
.
You can learn more about the related topics by checking out the following tutorials: