Regex exec only returning first match [duplicate]

RegExp.exec is only able to return a single match result at once.

In order to retrieve multiple matches you need to run exec on the expression object multiple times. For example, using a simple while loop:

var ptrn = /[a-zA-Z_][a-zA-Z0-9_]*|'(?:\\.|[^'])*'?|"(?:\\.|[^"])*"?|-?[0-9]+|#[^\n\r]*|./mg;

var match;
while ((match = ptrn.exec(input)) != null) {
    console.log(match);
}

This will log all matches to the console.

Note that in order to make this work, you need to make sure that the regular expression has the g (global) flag. This flag makes sure that after certain methods are executed on the expression, the lastIndex property is updated, so further calls will start after the previous result.

The regular expression will also need to be declared outside of the loop (as shown in the example above). Otherwise, the expression object would be recreated on every iteration and then the lastIndex would obviously reset every time, resulting in an infinite loop.

Leave a Comment