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']
#!/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')
#!/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')
除了正则表达式外,还可以使用列表理解,希望不是离题。
不能使用
match
,因为它从一开始就匹配。请改用findall
。输出:
['fun']
使用
search
只能得到第一个匹配项,因此请使用findall
。如果重叠匹配不是从同一点开始的,也可以使用
lookahead
。^{} module 具有命名列表(实际设置):
这里}方法而不是
words
只是一个名字,你可以用任何你喜欢的东西来代替。^在命名列表之前/之后使用{
.*
。要使用stdlib的
re
模块模拟命名列表:re.escape()
用于在单个单词中转义regex元字符,例如.*?
(按字面意思匹配单词)。sorted()
模拟regex
行为,并将最长的单词放在备选单词的第一位,比较:相关问题 更多 >
编程相关推荐