finding an exact match for string

前端 未结 2 1814
佛祖请我去吃肉
佛祖请我去吃肉 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.

    0 讨论(0)
  • 2021-01-14 15:31

    The problem with your initial method is that '\\b' does not denote the zero-width assertion search that your looking for. (And if it did, I would use r'\b' instead because backslashes can become a real hassle in regular expressions - see this link)

    From Regular Expression 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.

    Because - is a non-alphanumeric character, your findall regular expression will find award in award-wining but not in awards.

    Depending on your searched phrase, I would also think of using re.findall instead of re.match as suggested by Elazar. In your example re.match works, but if the word you are looking for is nested anywhere beyond the beginning of the string, re.match will not succeed.

    0 讨论(0)
提交回复
热议问题