在已知字符串中出现N次的情况下,查找在字符串中重复哪个术语

时间:2018-12-10 18:17:55

标签: python regex python-3.x

有什么方法可以执行以下操作,而无需使用蛮力之类的东西?

str = "abbcccddddefefef"
N = 3
repeated_term = func(str,N)

print(repeated_term )
> ['c','ef']


N = 2
term = func(str,N)

print(term)   
> ['b', 'dd', 'fe']    # Thanks to @blhsing for the correction!

以此类推...

1 个答案:

答案 0 :(得分:0)

您可以安装PyPi regex module(支持可变宽度后向模式),以使用正则表达式来查找精确重复N-1次的序列:

import regex
def func(s, N):
    return regex.findall(r'(?=(.+?)(?:\1){%d}(?!\1))(?<!\1)' % (N - 1), s)

这样:

func("abbcccddddefefef", 3)

返回:

['c', 'ef']

那:

func("abbcccddddefefef", 2)

返回:

['b', 'dd', 'fe']

请注意,您对N = 2的预期输出是不正确的,因为'dd''fe'都恰好发生了2次。