Exact match for words

前端 未结 1 814
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-26 12:43

I would like to use regular expression that matches if a sentence contains one of the words that I am looking for.

All of these are matching now which is not correct. I

相关标签:
1条回答
  • 2021-01-26 12:52

    As @CasimiretHippolyte pointed out you want to add word boundaries. If you don't want to manually do this for each word in your list, you need to modify your compiled regular expression.

    regex = re.compile(r'\b(?:%s)\b' % '|'.join(words))
    

    Note: If you have escape sequences in your regex, it's best to use raw string notation. By using a non-capturing (?:...) group, this allows your words to be grouped with word boundaries placed around them, otherwise it places a boundary at the very beginning and the very end.

    Ideone Demo

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