Regex? Match part of or whole word

前端 未结 5 1968
遥遥无期
遥遥无期 2021-01-25 23:33

I was wondering if it\'s possible to use regex with python to capture a word, or a part of the word (if it\'s at the end of the string).

Eg:
target word - potato

5条回答
  •  时光取名叫无心
    2021-01-25 23:57

    import re
    
    def get_matcher(word, minchars):
        reg = '|'.join([word[0:i] for i in range(len(word), minchars - 1, -1)])
        return re.compile('(%s)$' % (reg))
    
    matcher = get_matcher('potato', 4)
    for s in ["this is a sentence about a potato", "this is a sentence about a potat", "this is another sentence about a pota"]:
        print matcher.search(s).groups()
    

    OUTPUT

    ('potato',)
    ('potat',)
    ('pota',)
    

提交回复
热议问题