Check if Any Element in List Matches Regex in Python

This tutorial will discuss about a unique way to check if any element in list matches regex in Python.

We can use the Python’s regex module, to check if any element in the list of strings, matches a regex pattern or not.

Suppose we have a list of strings,

listObj = ["sample", "is", "text", "the", "why"]

We want to check if any string from this list starts with a substring “te”.

For this, we are going to use a regex pattern “^te” and the any() method.

Iterate over all the string elements of list and apply match() method from the regex module. If it returns a match object for any element then it means that any string from the list matches the regex pattern. If it returns None for all the strings, then it means no string from Lits matches the regex pattern.

During, iteration apply match() method on each element of list, and create a boolean list. Where, each true value denotes that the corresponding string in list starts with given prefix string. Pass that boolean sequence to any() method. It will return True, if sequence has any True value. It means it will return True if any string in List Matches the given Regex pattern.

Let’s see the complete example,

import re

# A list of strings
listObj = ["sample", "is", "text", "the", "why"]

# A Regex Pattern
pattern = "^te"

# Check if any string from list matches with regex pattern
if any(re.match(pattern, elem) for elem in listObj):
    print("Yes, At least one string in the List matches the regex pattern")
else:
    print("No string in the list matches the regex pattern")

Output

Yes, At least one string in the List matches the regex pattern

Summary

We learned how to check if Any Element in List Matches the Regex pattern in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top