finding an exact match for string

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

提交回复
热议问题