Python 替换重复的单词,不区分大小写

Python 替换重复的单词,不区分大小写,python,regex,python-3.x,Python,Regex,Python 3.x,样本: 预期: >>> line = 'the the, To to' >>> re.findall(r'\b(\w+) \1', line) ['the'] >>> re.findall(r'\b(\w+) \1', line, re.I) ['the', 'To'] >>> re.sub(r'\b(\w+) \1', r'\1', line, re.I) 'the, To to' 正则表达式在其他地方也可以使用,比如

样本:

预期:

>>> line = 'the the, To to'
>>> re.findall(r'\b(\w+) \1', line)
['the']
>>> re.findall(r'\b(\w+) \1', line, re.I)
['the', 'To']

>>> re.sub(r'\b(\w+) \1', r'\1', line, re.I)
'the, To to'
正则表达式在其他地方也可以使用,比如

  • Vim:
    s/\v读取:

    re.sub(模式、应答、字符串、计数=0、标志=0)

    您将
    re.I
    作为
    count
    传递(最多允许
    2个
    替换),而不是作为
    标志传递。相反,请尝试:

    'the, To'
    

    这不是一个真正的
    perl
    问题,是吗?但核心区别在于-您的模式中似乎没有任何地方有
    gi
    修饰符。@Sobrique OP有
    re.I
    ,忽略大小写标志,
    re.sub
    默认为“全局”;但是,他们没有正确地传递标志。@jonrsharpe真的需要添加单词boundry吗?@ShekharKhairnar我没有添加它,只是从问题中复制了OP的正则表达式。在这种情况下,这并不重要,但我假设他们正在处理可能相关的其他情况。是的,在需要的情况下,我需要避免替换像
    -如果没有
    \b
    ,它将改变
    t
    >>> re.sub(r'\b(\w+) \1', r'\1', s, flags=re.I)
                                      # ^ note
    'the, To'