Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match any string from a list of strings in regular expressions in python?

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?

like image 471
Josh Weinstein Avatar asked Oct 29 '15 05:10

Josh Weinstein


People also ask

How do you match a string to a list in Python?

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.

Which method will match the string Python?

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.

Which function returns a list of all matches in a string?

The findall() function returns a list containing all matches.


1 Answers

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.

like image 79
vks Avatar answered Oct 07 '22 04:10

vks