gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:30:54 28 4
gpt4 key购买 nike

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

([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']

关于python - 匹配任何重复两次的字符的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37162058/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com