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

2024-05-16 14:55:50 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个字符串列表

string_lst = ['fun', 'dum', 'sun', 'gum']

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

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

正确的方法是什么?或者必须创建多个正则表达式并将它们分别与字符串匹配?


Tags: 字符串inimportre列表forstringtemplate
3条回答

除了正则表达式外,还可以使用列表理解,希望不是离题。

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']
string_lst = ['fun', 'dum', 'sun', 'gum']
x="I love to have fun."

print re.findall(r"(?=("+'|'.join(string_lst)+r"))",x)

不能使用match,因为它从一开始就匹配。请改用findall

输出:['fun']

使用search只能得到第一个匹配项,因此请使用findall

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

^{} module具有命名列表(实际设置):

#!/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')

这里words只是一个名字,你可以用任何你喜欢的东西来代替。
^在命名列表之前/之后使用{}方法而不是.*

要使用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')

re.escape()用于在单个单词中转义regex元字符,例如.*?(按字面意思匹配单词)。
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']

相关问题 更多 >