Lets say I have a list of strings,
string_lst = ['fun', 'dum', 'sun', 'gum']
I want to make a regular expression, where at a point in it, I can match any of the strings i have in that list, within a group, such as this:
import re template = re.compile(r".*(elem for elem in string_lst).*") template.match("I love to have fun.")
What would be the correct way to do this? Or would one have to make multiple regular expressions and match them all separately to the string?
Python3. The any() function is used to check the existence of an element in the list. it's like- if any element in the string matches the input element, print that the element is present in the list, else, print that the element is not present in the list.
The re.search() and re. match() both are functions of re module in python. These functions are very efficient and fast for searching in strings. The function searches for some substring in a string and returns a match object if found, else it returns none.
The findall() function returns a list containing all matches.
Join the list on the pipe character |
, which represents different options in regex.
string_lst = ['fun', 'dum', 'sun', 'gum'] x="I love to have fun." print re.findall(r"(?=("+'|'.join(string_lst)+r"))", x)
Output: ['fun']
You cannot use match
as it will match from start. Using search
you will get only the first match. So use findall
instead.
Also use lookahead if you have overlapping matches not starting at the same point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With