开发者

RegExp.exec not returning global results

According to MDC https://developer.mozilla.org/en/JavaScr开发者_如何转开发ipt/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.


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;


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜