2 回答

TA貢獻1993條經驗 獲得超6個贊
制作自己的單詞邊界:
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
則不會成功。
添加回答
舉報