开发者

Regular expression test can't decide between true and false (JavaScript)

I get this behavior in both Chrome (Developer Tools) and Firefox (Firebug). Note the regex test returns alternating true/false values:

> var re = /.*?\bbl.*\bgr.*/gi;
undefined
> re
/.*?\\bbl.*\\bgr.*/gi
> re.test("Blue-Green");
true
> re.test("Blue-Green");
false
> re.test("Blue-Green");
true
> re.test("B开发者_如何学Golue-Green");
false

However, testing the same regex as a literal:

> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true

I can't explain this and it's making debugging very difficult. Can anyone explain this behavior?


/g (global) regexps will do that, yes.

See this question.

When you write a literal, you're getting a new regexp object every time, so losing the lastIndex state associated with the old object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜