正则表达式用于单词的重复

时间:2019-01-24 10:39:49

标签: python regex python-3.x design-patterns

我想找到“电话”模式,但它只给定一行中的一部电话:

pat=r'\sthe\sphone\s'
line=' the phone the phone '

如果我给输入字符串留有多余的空间=='电话'电话'它唯一会打印预期输出['the phone' ,'the phone']

ssss=re.findall(pat,line,re.IGNORECASE)

print(ssss)

输出[' the phone ']

我将 python 用于此正则表达式:

{pat=r'\sthe\sphone\s'

line=' the phone the phone '

ssss=re.findall(pat,line,re.IGNORECASE)

print(ssss)}

1 个答案:

答案 0 :(得分:0)

当您将模式应用于文本“ phone the phone”时,第一个匹配项将匹配“ phone”,而剩下的“ phone”不是以空格开头。

您可能要使用模式\bthe\sphone\b,其中\b是单词边界,可以确认您匹配的是完整单词而不是一个单词的一部分,但不会占用任何字符,解决您当前的问题。

这将比您当前的正则表达式匹配得更多,例如在This is the phone!>>>the phone<<<中匹配。

相关问题