python - 正则表达式与变量精确模式匹配

标签 python regex python-3.x

我需要从第一个列表中检测文本中的确切模式,但当它是其他单词的一部分时则不需要。我知道我可以使用 anchor 来完全匹配模式,但它不适用于变量。将感谢您的帮助!

lst = ['Test', 'Pink', 'Blue', 'Green']
text = 'Testing and Pink. Blue is my fav color. Greenwood is my name.'
def get_words_from_lst(text, lst):
    words = []        
    for word in lst:
        if r'{}'.format(word) in text:
            words.append(word)
    print(words)
get_words_from_lst(text, lst)

所需输出:['Pink', 'Blue']

最佳答案

使用带有边界(\b)的正则表达式

演示:

import re
lst = ['Test', 'Pink', 'Blue', 'Green']
text = 'Testing and Pink. Blue is my fav color. Greenwood is my name.'
def get_words_from_lst(text, lst):
    #print([word for word in lst if re.search(r"\b"+word+r"\b", text)])   #Single line list comprehension 
    words = []
    for word in lst:
        if re.search(r"\b"+word+r"\b", text):
            words.append(word)
    print(words)
get_words_from_lst(text, lst)

输出:

['Pink', 'Blue']

关于python - 正则表达式与变量精确模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50534417/

相关文章:

python - "with io.open"是否自动关闭文件?

python - 将 value-dict 重新映射到 Pandas 中的列

regex - 匹配第一个冒号之前的所有内容,包括冒号和后面的空格

regex - 当连字符围绕单个内部字符时如何替换词内连字符

javascript - 如何生成保留标点符号的简单字谜?

python - 即使基本情况是完美的,递归也不会终止

python - 连接 Pandas 日期时间

python - Google App Engine 项目中未显示 html 中的嵌入图像

python - 如何解析Python语法?

c++ - 使用 boost::python 从 C++ 创建 python collections.namedtuple