How to code a Regex for a shared character between two correspondent patterns?

Retro Code :

I am going to find all 'aa' sub-strings in the 'caaab'. So, I've used the following regular expression.

/aa/g

Using the cited expression, I expect that JavaScript's match method returns two correspondent patterns. As you can see, the middle, shared 'a' causes two 'aa' patterns! Nonetheless, it merely returns the first one. What is the problem with the Regex, and how can I fix it?

let foundArray=d.match(/aa/g);

AD7six :

Use a lookahead

As mentioned in a comment that's how regexes are designed to work:

it's working exactly as it's supposed to; once it consumes a character, it moves past it

Matches do not overlap, this isn't a limitation of js it's simply how regular expressions work.

The way to get around that is to use a zero-length match, i.e. a look-ahead or look-behind

Tim's existing answer already does this, but can be simplified as follows:

match = "caaab".match(/a(?=a)/g);
console.log(match);

This is finding an a followed by another a (which is not returned as part of the match). So technically it's finding:

caaab
 ^ first match, single character
  ^ second match, single character

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11730&siteId=1