Assume the following code:
"ab00ab____ab01ab".match(/ab(.+)ab/);
I want this to get me 00
and 01
, but instead it returns me this:
["ab00ab____ab01ab", "00ab____ab01"]
How can I fix this problem?
Assume the following code:
"ab00ab____ab01ab".match(/ab(.+)ab/);
I want this to get me 00
and 01
, but instead it returns me this:
["ab00ab____ab01ab", "00ab____ab01"]
How can I fix this problem?
Use RegExp#exec
inside a loop with the /ab(.+?)ab/g
regex:
var s = "ab00ab____ab01ab";
var re = /ab(.+?)ab/g;
var res = [];
while ((m=re.exec(s)) !== null) {
res.push(m[1]);
}
console.log(res);
First of all, you need a lazy dot matching pattern (.*?
or .+?
) to match up to the first ab
, not a greedy one (.+
) matching up to the last ab
. Also, with String#match
and a regex with a global modifier, you lose all the captures (those substrings matched with the parenthesized regex pattern parts), you can only have them with the RegExp#exec
.