我们的文本为
"Google and Bert+Amazon+Alexa'
预期的输出是当我们传递搜索文本作为 Google 和 Bert 时,输出应该是“Google 和 Bert”,并且当输入搜索词是 Google 时它不应该匹配。需要匹配完整的文本,可以在符号“+”之前或之间或之后
pattern = r'(?:^|\+)' + 'Amazon' + '(?:$|\+)'
re.search(pattern, "Google and Bert+Amazon+Alexa").group()
Output is: +Amazon+ but the expected output is Amazon
最佳答案
实际上,这里不需要正则表达式,只需用 +
分割字符串并检查 search
是否在结果列表中:
s = "Google and Bert+Amazon+Alexa"
search = "Google and Bert"
if search in s.split('+'):
print(search)
else:
print("NO MATCH!")
请参阅Python demo .
s.split('+')
的结果将是 ['Google and Bert', 'Amazon', 'Alexa']
并且您将搜索对于此列表中的 Google 和 Bert
,并返回/显示搜索短语。
关于正则表达式方法,您可以尝试类似 pattern = r'(?:^|\+)(' + re.escape(search) + ')(?:$|\+)'
然后是 re.search(pattern, "Google and Bert+Amazon+Alexa").group(1)
,但这似乎并不是您真正需要的。
关于Python正则表达式提取带有+符号的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57975575/