Python | Check if string matches regex list
Last Updated :
23 Apr, 2023
Sometimes, while working with Python, we can have a problem we have list of regex and we need to check a particular string matches any of the available regex in list. Let's discuss a way in which this task can be performed.
Method : Using join regex + loop + re.match() This task can be performed using combination of above functions. In this, we create a new regex string by joining all the regex list and then match the string against it to check for match using match() with any of the element of regex list.
Python3
# Python3 code to demonstrate working of
# Check if string matches regex list
# Using join regex + loop + re.match()
import re
# initializing list
test_list = ["gee*", "gf*", "df.*", "re"]
# printing list
print("The original list : " + str(test_list))
# initializing test_str
test_str = "geeksforgeeks"
# Check if string matches regex list
# Using join regex + loop + re.match()
temp = '(?:% s)' % '|'.join(test_list)
res = False
if re.match(temp, test_str):
res = True
# Printing result
print("Does string match any of regex in list ? : " + str(res))
OutputThe original list : ['gee*', 'gf*', 'df.*', 're']
Does string match any of regex in list ? : True
Another approach could be using a regular expression library like 'fnmatch' which can use 'filter' function to check if the string matches any of the regex in the list, this approach would have a time complexity of O(n) where n is the number of regex in the list and a space complexity of O(1) as it does not require any additional data structures.
Python3
import fnmatch
# initializing list
test_list = ["gee*", "gf*", "df.*", "re"]
# printing list
print("The original list : " + str(test_list))
# initializing test_str
test_str = "geeksforgeeks"
# Check if string matches regex list
# Using filter + fnmatch
res = bool(list(filter(lambda x: fnmatch.fnmatch(test_str, x), test_list)))
# Printing result
print("Does string match any of regex in list ? : " + str(res))
OutputThe original list : ['gee*', 'gf*', 'df.*', 're']
Does string match any of regex in list ? : True
The complexity analysis for this approach depends on the size of the input list and the length of the input string.
- The filter function is used to filter elements from the test_list that match the given regular expression (in this case, fnmatch.fnmatch(test_str, x)). The time complexity of the filter function is O(n), where n is the number of elements in the input list.
- The fnmatch.fnmatch function is used to match the input string with each regular expression in the filtered list. The time complexity of this function is O(k), where k is the length of the input string.
- The list function is used to convert the filtered result into a list. The time complexity of this function is O(n), where n is the number of elements in the filtered list.
Overall, the time complexity of this approach is O(n*k) where n is the number of elements in the input list and k is the length of the input string.
Auxiliary Space is O(n)
Method 3 : using fnmatch library
- Import the fnmatch library.
- Use a list comprehension to create a list of Boolean values indicating whether each regular expression in test_list matches test_str using fnmatch.fnmatch().
- Check if True exists in the list created in step 2 using the any() function.
- Print the result.
Python3
import fnmatch
# initializing list
test_list = ["gee*", "gf*", "df.*", "re"]
# printing list
print("The original list : " + str(test_list))
# initializing test_str
test_str = "geeksforgeeks"
# Check if string matches regex list
# Using list comprehension + fnmatch
res = any(fnmatch.fnmatch(test_str, pattern) for pattern in test_list)
# Printing result
print("Does string match any of regex in list ? : " + str(res))
OutputThe original list : ['gee*', 'gf*', 'df.*', 're']
Does string match any of regex in list ? : True
Time complexity: O(n), where n is the number of regular expressions in test_list.
Auxiliary space: O(1) for res, O(n) for the list comprehension created in step 2.
Similar Reads
Python | Check if suffix matches with any string in given list Given a list of strings, the task is to check whether the suffix matches any string in the given list. Examples: Input: lst = ["Paras", "Geeksforgeeks", "Game"], str = 'Geeks' Output: TrueInput: lst = ["Geeks", "for", "forgeeks"], str = 'John' Output: False Let's discuss a few methods to do the task
6 min read
Python - Check for spaces in string Sometimes, while working with strings in Python, we need to determine if a string contains any spaces. This is a simple problem where we need to check for the presence of space characters within the string. Let's discuss different methods to solve this problem.Using 'in' operator'in' operator is one
3 min read
Python | Get matching substrings in string The testing of a single substring in a string has been discussed many times. But sometimes, we have a list of potential substrings and check which ones occur in a target string as a substring. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension Using l
6 min read
Python | Check if any String is empty in list Sometimes, while working with Python, we can have a problem in which we need to check for perfection of data in list. One of parameter can be that each element in list is non-empty. Let's discuss if a list is perfect on this factor using certain methods. Method #1 : Using any() + len() The combinati
6 min read
Python - Extract numbers from list of strings We are given a list of string we need to extract numbers from the list of string. For example we are given a list of strings s = ['apple 123', 'banana 456', 'cherry 789'] we need to extract numbers from the string in list so that output becomes [123, 456, 789].Using Regular ExpressionsThis method us
2 min read
Python - Check if String contains any Number We are given a string and our task is to check whether it contains any numeric digits (0-9). For example, consider the following string: s = "Hello123" since it contains digits (1, 2, 3), the output should be True while on the other hand, for s = "HelloWorld" since it has no digits the output should
2 min read
Python - Substring presence in Strings List Given list of substrings and list of string, check for each substring, if they are present in any of strings in List. Input : test_list1 = ["Gfg", "is", "best"], test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"] Output : [True, False, False] Explanation : Only Gfg is present as subst
5 min read
How to Use Regex with os.listdir() in Python? We are given a file path and our task is to find out the usage of regex with os.listdir() in Python by using that path and files inside that directory. In this article, we will see the usage of Regex with os.listdir() in Python with code examples. Regex with os.listdir() in PythonIn Python, the os.l
3 min read
Python - Remove Non-English characters Strings from List Given a List of Strings, perform removal of all Strings with non-english characters. Input : test_list = ['Good| ????', '??Geeks???'] Output : [] Explanation : Both contain non-English characters Input : test_list = ["Gfg", "Best"] Output : ["Gfg", "Best"] Explanation : Both are valid English words.
8 min read
Python Extract Substring Using Regex Python provides a powerful and flexible module called re for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings. In this article, we'll explore four simple a
2 min read