Let\'s say I have the string
\"12345\"
If I .match(/\\d{3}/g)
, I only get one match, \"123\"
. Why don\'t I get
You can't do this with a regex alone, but you can get pretty close:
var pat = /(?=(\d{3}))\d/g;
var results = [];
var match;
while ( (match = pat.exec( '1234567' ) ) != null ) {
results.push( match[1] );
}
console.log(results);
In other words, you capture all three digits inside the lookahead, then go back and match one character in the normal way just to advance the match position. It doesn't matter how you consume that character; .
works just as well \d
. And if you're really feeling adventurous, you can use just the lookahead and let JavaScript handle the bump-along.
This code is adapted from this answer. I would have flagged this question as a duplicate of that one, but the OP accepted another, lesser answer.