Match exact phrase within a string in Python

后端 未结 5 555
梦如初夏
梦如初夏 2020-12-18 10:13

I\'m trying to determine whether a substring is in a string. The issue I\'m running into is that I don\'t want my function to return True if the substring is found within an

5条回答
  •  星月不相逢
    2020-12-18 10:31

    Since your phrase can have multiple words, doing a simple split and intersect won't work. I'd go with regex for this one:

    import re
    
    def is_phrase_in(phrase, text):
        return re.search(r"\b{}\b".format(phrase), text, re.IGNORECASE) is not None
    
    phrase = "Purple cow"
    
    print(is_phrase_in(phrase, "Purple cows make the best pets!"))   # False
    print(is_phrase_in(phrase, "Your purple cow trampled my hedge!"))  # True
    

提交回复
热议问题