且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式?匹配部分或整个单词

更新时间:2022-03-12 22:24:19

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()

输出

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