Regular expression for fixed width matches

so I have a line:


And I want to find all groups of type aXXXb where X is any char. I thought the regex was:


will do the trick, but it only gets the first one:

' aaggb b'

and skips the second:

'a aggbb

How do I get both?

I've searched around for a while trying to figure this out, so I hope I haven't missed something very obvious. Thank!


source to share

1 answer

If you want to get fixed length substrings, you need to specify it using a limit quantifier {3}

(matches exactly 3 characters) and use capturing inside the look to match all substrings:



Watch the demo

Look-ahead consumes no characters and allows overlapping matches. "Consumption" means that after the closing or closing of the closing parenthesis, the regex engine stays at the same place on the line it started searching from: it doesn't move. From this position, the engine can start matching characters again. (from )

var re = /(?=(a.{3}b))/g; 
var str = 'aaggbb';

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
    document.getElementById("demo").innerHTML += m[1] + "<br/>";

<div id="demo" />

Run codeHide result



All Articles