Python正则表达式提取带有+符号的单词

标签 python regex python-3.x

我们的文本为

"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/

相关文章:

c - 使用 PCRE 正则表达式的奇怪答案

python - 尝试循环网页进行数据抓取时出错

python - 我可以获得应用于函数的装饰器列表吗?

python - 如何在Python中创建全局变量

Python - 仅一种类型的集合

python - 我可以在 Restplus 模型旁边添加用户定义的错误消息吗?

python-3.x - 停用 pipenv 环境

python - Theano:函数内张量变量的形状

javascript - 使用 javascript 的替换通配符来更改字符串内的宽度属性

Ruby 用捕获的正则表达式模式替换字符串