Search code examples
javascriptregexreplicationstring-length

Regex - string repetition of min length


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.


Solution

  • 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+.

    To only find repetitions of 2+ character chunks you may use a lazy limiting quantifier {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.