Match exact phrase within a string in Python

后端 未结 5 541
梦如初夏
梦如初夏 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:30

    One can do this very literally with a loop

    phrase = phrase.lower()
    text = text.lower()
    
    answer = False 
    j = 0
    for i in range(len(text)):
        if j == len(phrase):
            return text[i] == " "
        if phrase[j] == text[i]:
            answer = True
            j+=1
        else:
            j = 0 
            answer = False 
    return answer
    

    Or by splitting

    phrase_words = phrase.lower().split()
    text_words = text.lower().split()
    
    return phrase_words in text_words
    

    or using regular expressions

    import re
    pattern = re.compile("[^\w]" + text + ""[^\w]")
    pattern.match(phrase.lower())
    

    to say that we want no characters preceding or following our text, but whitespace is okay.

提交回复
热议问题