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

后端 未结 5 1295
深忆病人
深忆病人 2020-12-01 10:50

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

5条回答
  •  有刺的猬
    2020-12-01 11:27

    Except for the regular expression, you can use list comprehension, hope it's not off the topic.

    import re
    def match(input_string, string_list):
        words = re.findall(r'\w+', input_string)
        return [word for word in words if word in string_list]
    
    >>> string_lst = ['fun', 'dum', 'sun', 'gum']
    >>> match("I love to have fun.", string_lst)
    ['fun']
    

提交回复
热议问题