Skip to main content
 首页 » 编程设计

python之匹配任何重复两次的字符的正则表达式

2025年04月02日36exmyth

我正在尝试确定所提供的字符串是否包含恰好重复两次的字符。以下是我使用的正则表达式:

([a-z])\1(?!\1) 

但是,当针对以下字符串进行测试时,下面的两个字符串都匹配该模式(尽管我使用了 (?!\1)):

>>> re.findall(r'.*([a-z])\1(?!\1)', 'abcdeefg') 
['e'] 
>>> re.findall(r'.*([a-z])\1(?!\1)', 'abcdeeefg') 
['e'] 

上面的模式有什么问题?

请您参考如下方法:

我怀疑单独使用 python 正则表达式无法满足您的需求。为了确保一个字符恰好重复两次,将需要对断言进行否定的检查,并且此类断言不能包含组引用。

最简单的方法是查找所有重复项并简单地检查它们的长度。

def double_repeats(txt): 
    import itertools 
 
    # find possible repeats 
    candidates = set(re.findall(r'([a-z])\1', txt)) 
 
    # now find the actual repeated blocks 
    repeats = itertools.chain(*[re.findall(r"({0}{0}+)".format(c), txt) for c in candidates]) 
 
    # return just the blocks of length 2 
    return [x for x in repeats if len(x) == 2] 

然后:

>>> double_repeats("abbbcbbdddeffgggg") 
['ff', 'bb']