String exact match

后端 未结 7 1653
悲哀的现实
悲哀的现实 2020-11-29 08:13

I have a string in which the word \"LOCAL\" occurs many times. I used the find() function to search for this word but it returns another word \"Locally\" as wel

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 08:51

    Using Pyparsing:

    import pyparsing as pp
    
    def search_exact_word_in_string(phrase, text):
    
        rule = pp.ZeroOrMore(pp.Keyword(phrase))  # pp.Keyword() is case sensitive
        for t, s, e in rule.scanString(text):
          if t:
            return t
        return False
    
    text = "Local locally locale"
    search = "Local"
    print(search_exact_word_in_string(search, text))
    

    Which Yields:

    ['Local']

提交回复
热议问题