如何匹配python中正则表达式中字符串列表中的任何字符串?

Jos*_*ein 17 python regex string python-3.x

可以说我有一个字符串列表,

string_lst = ['fun', 'dum', 'sun', 'gum']
Run Code Online (Sandbox Code Playgroud)

我想制作一个正则表达式,在其中的某个点,我可以匹配该列表中的任何字符串,在一个组中,例如:

import re
template = re.compile(r".*(elem for elem in string_lst).*")
template.match("I love to have fun.")
Run Code Online (Sandbox Code Playgroud)

这样做的正确方法是什么?或者,是否必须制作多个正则表达式并将它们全部分别匹配到字符串?

vks*_*vks 21

string_lst = ['fun', 'dum', 'sun', 'gum']
x="I love to have fun."

print re.findall(r"(?=("+'|'.join(string_lst)+r"))",x)
Run Code Online (Sandbox Code Playgroud)

您无法使用,match因为它将从start.Use匹配findall.

输出:['fun']

使用search你只会获得第一场比赛findall.所以请改用.

lookahead如果重叠匹配不是从同一点开始,也可以使用.

  • 但是如果有像有趣这样的词,这将返回`['fun']` (2认同)

jfs*_*jfs 11

regex模块命名列表(实际设置):

#!/usr/bin/env python
import regex as re # $ pip install regex

p = re.compile(r"\L<words>", words=['fun', 'dum', 'sun', 'gum'])
if p.search("I love to have fun."):
    print('matched')
Run Code Online (Sandbox Code Playgroud)

words只是一个名字,你可以使用你喜欢的任何东西.
.search()使用方法而不是.*命名列表之前/之后.

使用stdlib的re模块模拟命名列表:

#!/usr/bin/env python
import re

words = ['fun', 'dum', 'sun', 'gum']
longest_first = sorted(words, key=len, reverse=True)
p = re.compile(r'(?:{})'.format('|'.join(map(re.escape, longest_first))))
if p.search("I love to have fun."):
    print('matched')
Run Code Online (Sandbox Code Playgroud)

re.escape()用于逃避正则表达式元字符,例如.*?单个单词内部(以字面匹配单词).
sorted()模拟regex行为,并将最长的单词放在备选方案中,比较:

>>> import re
>>> re.findall("(funny|fun)", "it is funny")
['funny']
>>> re.findall("(fun|funny)", "it is funny")
['fun']
>>> import regex
>>> regex.findall(r"\L<words>", "it is funny", words=['fun', 'funny'])
['funny']
>>> regex.findall(r"\L<words>", "it is funny", words=['funny', 'fun'])
['funny']
Run Code Online (Sandbox Code Playgroud)


Joh*_*ooy 6

在组合成正则表达式之前,您应该确保正确转义字符串

>>> 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']
Run Code Online (Sandbox Code Playgroud)


lor*_*. j 5

除了正则表达式之外,您还可以使用列表理解,希望这没有偏离主题。

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']
Run Code Online (Sandbox Code Playgroud)