Copyimport re
regexes = [
"foo.*",
"bar.*",
"qu*x"
]
# Make a regex that matches if any of our regexes match.
combined = "(" + ")|(".join(regexes) + ")"
if re.match(combined, mystring):
print "Some regex matched!"
Answer from Ned Batchelder on Stack OverflowCopyimport re
regexes = [
"foo.*",
"bar.*",
"qu*x"
]
# Make a regex that matches if any of our regexes match.
combined = "(" + ")|(".join(regexes) + ")"
if re.match(combined, mystring):
print "Some regex matched!"
Copyimport re
regexes = [
# your regexes here
re.compile('hi'),
# re.compile(...),
# re.compile(...),
# re.compile(...),
]
mystring = 'hi'
if any(regex.match(mystring) for regex in regexes):
print 'Some regex matched!'
Matching a list of regex to every string in a list one by one
How to regex match list of patterns in python
How to regex match list of patterns in python - Stack Overflow
Is there a way in python to apply a list of regex patterns that are stored in a list to a single string? - Stack Overflow
Videos
I have list of patterns and I need to return that pattern if that is present in the given string else return None. I tried with the below code using re module , but I am getting only null in "matches" (when I tried to print matches). Completely new to corepython and regex,kindly help
import re
patterns_lst=['10_TEST_Comments','10_TEST_Posts','10_TEST_Likes']
def get_matching pattern(filename):
for pattern in patterns_lst:
matches = re.(pattern,filename)
if matches:
return matches
else:
return None
print(get_matching pattern("6179504_10_TEST_Comments_22-Nov-2021_22-Nov-2021.xlsx"))
Full Example (Python 3):
For Python 2.x look into Note below
import re
mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
r = re.compile(".*cat")
newlist = list(filter(r.match, mylist)) # Read Note below
print(newlist)
Prints:
['cat', 'wildcat', 'thundercat']
Note:
For Python 2.x developers, filter returns a list already. In Python 3.x filter was changed to return an iterator so it has to be converted to list (in order to see it printed out nicely).
Python 3 code example
Python 2.x code example
You can create an iterator in Python 3.x or a list in Python 2.x by using:
filter(r.match, list)
To convert the Python 3.x iterator to a list, simply cast it; list(filter(..)).