最小长度的字符串重复

时间:2021-03-04 11:51:03

I want to find any string repetition. I have following code:

我想找到任何字符串的重复。我有如下代码:

let match: Object;
let repetition: ?string;
while ((match = /(.+?)\1+/g.exec(string)) !== null && repetition === null) {
  repetition = match[1];
}

It finds 'abc' replication in 'weabcabcjy', but it also finds 'll' in 'all'. I would like to have regex to limit minimal length of replication to 2 characters. It means it compare always minimally 2 characters against others two.

它可以在“weabcabcjy”中找到“abc”的复制,也可以在“all”中找到“ll”。我希望regex将复制的最小长度限制为2个字符。这意味着它总是将两个字符与其他两个字符进行最小的比较。

1 个解决方案

#1


2  

The .+? pattern finds any one or more chars other than linebreak characters, so ll in all will get matched since the first l will be captured into Group 1 and the second one will be matched with \1+.

. + ?pattern查找除换行符之外的任何一个或多个字符,因此ll将被匹配,因为第一个l将被捕获到组1中,第二个l将与\1+匹配。

To only find repetitions of 2+ character chunks you may use a lazy limiting quantifier {2,}?:

为了只找到2+字符块的重复,您可以使用一个延迟限制量词{2,}?:

/(.{2,}?)\1+/g

See the regex demo.

查看演示正则表达式。

The (.{2,}?)\1+ pattern will match and capture into Group 1 any two or more, but as few as possible, characters other than linebreak symbols and then 1 or more same consecutive substrings.

(.{2,}?)\1+模式将匹配并捕获到组1中任何两个或多个,但尽可能少,除了换行符符号和一个或多个相同的连续子字符串之外的字符。

#1


2  

The .+? pattern finds any one or more chars other than linebreak characters, so ll in all will get matched since the first l will be captured into Group 1 and the second one will be matched with \1+.

. + ?pattern查找除换行符之外的任何一个或多个字符,因此ll将被匹配,因为第一个l将被捕获到组1中,第二个l将与\1+匹配。

To only find repetitions of 2+ character chunks you may use a lazy limiting quantifier {2,}?:

为了只找到2+字符块的重复,您可以使用一个延迟限制量词{2,}?:

/(.{2,}?)\1+/g

See the regex demo.

查看演示正则表达式。

The (.{2,}?)\1+ pattern will match and capture into Group 1 any two or more, but as few as possible, characters other than linebreak symbols and then 1 or more same consecutive substrings.

(.{2,}?)\1+模式将匹配并捕获到组1中任何两个或多个,但尽可能少,除了换行符符号和一个或多个相同的连续子字符串之外的字符。