finding an exact match for string

前端 未结 2 1835
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-14 14:44

I used the following function to find the exact match for words in a string.

def exact_Match(str1, word):
    result = re.findall(\'\\\\b\'+word+\'\\\\b\'         


        
2条回答
  •  無奈伤痛
    2021-01-14 15:09

    Make your own word-boundary:

    def exact_Match(phrase, word):
        b = r'(\s|^|$)' 
        res = re.match(b + word + b, phrase, flags=re.IGNORECASE)
        return bool(res)
    

    copy-paste from here to my interpreter:

    >>> str1 = "award-winning blueberries"
    >>> word1 = "award"
    >>> word2 = "award-winning"
    >>> exact_Match(str1, word1)
    False
    >>> exact_Match(str1, word2)
    True
    

    Actually, the casting to bool is unnecessary and not helping at all. The function is better off without it:

    def exact_Match(phrase, word):
        b = r'(\s|^|$)' 
        return re.match(b + word + b, phrase, flags=re.IGNORECASE)
    

    note: exact_Match is pretty unconventional casing. just call it exact_match.

提交回复
热议问题