views:

24

answers:

2

According to MDC https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec the following code should log each of the global matches for this regexp.

var str = "(^|\\+)(1\\+1)($|\\+)";
var regex = new RegExp(str, "g");
var result;
var testString = "1+1+1";
while ((result = regex.exec(testString)) != null)
{
    console.log(result);
}

But all I get is the first match and then the loop finishes. Any ideas why.

A: 

There's only one match, since overlapping is not allowed. The match is:

(^|\\+) - ^

(1\\+1) - 1+1

($|\\+) - +

It should be clear there can't be another match, since every match requires at least 1+1, and there's only a single 1 left. As a separate note, using a regex literal is simpler:

var regex = /(^|\+)(1\+1)($|\+)/g;
Matthew Flaschen
I didn't realise global matches couldn't overlap. Is there anyway I can get overlapping matches matched by a regexp?
wheresrhys
I don't know a way, other than the obvious (inefficient) approach of running it on `testString.substring(0)`, `testString.substring(1)`, etc.
Matthew Flaschen
It's a shame as I'm having to use nested loops for what is actually a more complicated situation than the simplified example in the question), though it's still a pretty simple task and one which I though regex would be ideally suited to.
wheresrhys
A: 

Your regular expression won't match that string more than once since the matches can't overlap. Do you have another sample string you're trying to match, or more details on what you need from the string?

Regardless, I would use a RegExp object literal instead; less escaping and you can specify the global flag directly.

var regex = /(^|\+)(1\+1)($|\+)/g;
Clay Hinson