Python:动态组成的正则表达式在finditer中不起作用

时间:2019-08-07 13:40:32

标签: python regex

我想在句子中找到匹配的词,并动态提供该词。我编写了与示例兼容的以下代码:

text="Algorithmic detection of misinformation and disinformation Gricean perspectives"
found=re.finditer(r"\bdetection\b", text)
for i in found:
    print("found") #this line prints exactly once

但是由于我需要目标词作为先验未知的输入,因此我更改了如下代码,并停止了工作:

text="Algorithmic detection of misinformation and disinformation Gricean perspectives"
word="detection" #or passed by other functions etc.
found=re.finditer(r"\b"+word+"\b", text)
for i in found:
    print("found") #this line does not print in this piece of code

我应该如何更正我的代码?谢谢

2 个答案:

答案 0 :(得分:1)

found=re.finditer(r"\b"+word+r"\b", text)
#         raw string here ___^

答案 1 :(得分:1)

仅使用Raw f-strings

text = "Algorithmic detection of misinformation and disinformation Gricean perspectives"
word = "detection"  # or passed by other functions etc.
pat = re.compile(fr"\b{word}\b")   # precompiled pattern
found = pat.finditer(text)
for i in found:
    print("found")