Samuel Alvarez
Samuel Alvarez

Reputation: 25

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 the last two a's.

Something like this:

Upvotes: 0

Views: 696

Answers (2)

GauravLuthra
GauravLuthra

Reputation: 1035

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

Upvotes: 1

xianshenglu
xianshenglu

Reputation: 5359

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);

Upvotes: 3

Related Questions