为了账号安全,请及时绑定邮箱和手机立即绑定

查找与字符串完全匹配的字符串

查找与字符串完全匹配的字符串

沧海一幻觉 2021-03-02 17:13:07
我使用以下函数来查找字符串中单词的完全匹配。def exact_Match(str1, word):    result = re.findall('\\b'+word+'\\b', str1, flags=re.IGNORECASE)    if len(result)>0:        return True    else:        return Falseexact_Match(str1, word)但是当“ award”和“ award-winning”这两个词仅应在以下字符串中获奖时,我得到了一个完全匹配的词。str1 = "award-winning blueberries"word1 = "award"word2 = "award-winning"我如何才能使re.findall将整个单词与连字符和其他标点符号匹配?
查看完整描述

2 回答

?
ibeautiful

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是相当非常规的外壳。只需将其称为精确匹配即可。


查看完整回答
反对 回复 2021-03-27
?
慕容3067478

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.matchElazar的建议。在您的示例中re.match可以运行,但是如果您要查找的单词嵌套在字符串开头之外的任何位置,re.match则不会成功。


查看完整回答
反对 回复 2021-03-27
  • 2 回答
  • 0 关注
  • 237 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号