Skip to content Skip to sidebar Skip to footer

How To Match An Overlapping Pattern Multiple Times Using Regexp

Is there a way with a RegExp that given the regex /aa/g (or similar) it matches two times the string 'aaa'? Given that the first match is the first two a's, and the second match is

Solution 1:

you can change the lastIndex of reg to the index+1

let str = "aaa",
  reg = /aa/g,
  next = reg.exec(str),
  res = [];
while (next) {
  res.push(next[0]);
  reg.lastIndex = next.index + 1;
  next = reg.exec(str);
}
console.log(res);

Solution 2:

You can capture two a's inside lookahead and then go back & match one a character.

let pattern = /(?=(a{2}))a/g;
    let resultMatches = [];
    let match;
    let stringToCheck = 'aaa';

    while ((match = pattern.exec(stringToCheck)) !== null)
        resultMatches.push(match[1]);

    console.log(resultMatches);

Using 'aaa' as input returns [ 'aa', 'aa' ], whereas using 'aaaa' as input would return [ 'aa', 'aa', 'aa' ]

Post a Comment for "How To Match An Overlapping Pattern Multiple Times Using Regexp"