Zero-Length regexes and infinite matches?

You selected JavaScript regex flavor at regexr.com online regex tester. JavaScript regex engine does not move the index automatically when a pattern that can match an empty string is passed.

That is why when you need to emulate the behavior observed in .NET Regex.Matches, PHP preg_match_all, Python re.finditer, etc. you need to manually advance the index to test each position.

See regex101.com test:

var re = /a*/g; 
var str = 'dgwawa';
var m;
 
while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {   // <- this part
        re.lastIndex++;               // <- here
    }                                 // <- is important
    document.body.innerHTML += "'" + m[0] + "'<br/>";
}

If you remove that if block, you will get an infinite loop.

There are two very important things to mention with this regard:

  • Always use appropriate online regex tester for your programming language
  • Avoid using unanchored patterns that can match empty strings

Tags:

Regex