2 回答

TA贡献1993条经验 获得超5个赞
制作自己的单词边界:
def exact_Match(phrase, word):
b = r'(\s|^|$)'
res = re.match(b + word + b, phrase, flags=re.IGNORECASE)
return bool(res)
从这里复制粘贴到我的解释器中:
>>> str1 = "award-winning blueberries"
>>> word1 = "award"
>>> word2 = "award-winning"
>>> exact_Match(str1, word1)
False
>>> exact_Match(str1, word2)
True
实际上,强制转换bool是不必要的,根本没有帮助。没有它,功能会更好:
def exact_Match(phrase, word):
b = r'(\s|^|$)'
return re.match(b + word + b, phrase, flags=re.IGNORECASE)
注意:exact_Match是相当非常规的外壳。只需将其称为精确匹配即可。

TA贡献1773条经验 获得超3个赞
您的初始方法的问题在于,'\\b'
它并不表示您要寻找的零宽度断言搜索。(如果这样做的话,我会改用r'\b'
反斜杠,因为反斜杠可能会成为正则表达式中真正的麻烦-请参阅此链接)
从正则表达式HOWTO
\b
Word boundary. This is a zero-width assertion that matches only at the beginning or end of a word. A word is defined as a sequence of alphanumeric characters, so the end of a word is indicated by whitespace or a non-alphanumeric character.
因为-
是非字母数字字符,所以findall正则表达式将award
在中找到,award-wining
但不会在中找到awards
。
根据您搜索的短语,我也会考虑使用re.findall
而不是re.match
Elazar的建议。在您的示例中re.match
可以运行,但是如果您要查找的单词嵌套在字符串开头之外的任何位置,re.match
则不会成功。
添加回答
举报