
您可以使用re模块。
>>> s = 'foo foo bar bar'>>> re.sub(r'b(.+)s+1b', r'1', s)'foo bar'>>> s = 'foo bar foo bar foo bar'>>> re.sub(r'b(.+)s+1b', r'1', s)'foo bar foo bar'
如果要匹配任意数量的连续出现:
>>> s = 'foo bar foo bar foo bar'>>> re.sub(r'b(.+)(s+1b)+', r'1', s)'foo bar'
编辑。最后一个示例的附加内容。为此,当短语重复时,您必须调用re.sub。所以:
>>> s = 'this is a sentence sentence sentence this is a sentence where phrases phrases duplicate where phrases duplicate'>>> while re.search(r'b(.+)(s+1b)+', s):... s = re.sub(r'b(.+)(s+1b)+', r'1', s)...>>> s'this is a sentence where phrases duplicate'
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)