If you want to get capture groups in a global regex, you can't use match
, unfortunately. Instead you'll need to use exec
on the regex:
var myregex = /^.(.*).$/gm;
var result, allMatches = [];
while((result = myregex.exec(mystring)) != null) {
var match = result[1]; // get the first match pattern of this match
allMatches.push(match);
}
With a global regex, match
returns an array of all the whole matches and never returns capture groups. exec
returns a single match and all of its capture groups. To get all the matches, you must call exec
multiple times until it finally returns null
.
Note that exec
relies on the regex maintaining state, so you must save the regex in a variable:
while((result = /^.(.*).$/gm.exec(mystring)) != null) // BAD and WRONG!
This is wrong because with each loop, there is a fresh regex which doesn't know what match it is supposed to be returning this loop. (Or, more precisely, it doesn't know the lastIndex
of the previous regex.)