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

后端 未结 5 1326
深忆病人
深忆病人 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:32

    You should make sure to escape the strings correctly before combining into a regex

    >>> import re
    >>> string_lst = ['fun', 'dum', 'sun', 'gum']
    >>> x = "I love to have fun."
    >>> regex = re.compile("(?=(" + "|".join(map(re.escape, string_lst)) + "))")
    >>> re.findall(regex, x)
    ['fun']
    

提交回复
热议问题