最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Regular expression test can't decide between true and false (JavaScript) - Stack Overflow

programmeradmin6浏览0评论

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("Blue-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?

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("Blue-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?

Share Improve this question edited May 27, 2010 at 0:11 Earlz 64k100 gold badges313 silver badges507 bronze badges asked Apr 19, 2010 at 18:29 nw.nw. 2,2266 gold badges31 silver badges42 bronze badges 4
  • Funky. Reproduced w/ Firefox 3.5.8 and Firebug 1.5.3. Still occurs if "Blue-Green" is stored into a variable and re-used. – Darien Commented Apr 19, 2010 at 18:34
  • I found this to be mildly amusing. Instead of using a = !a to switch between true/false, why don't we define a private regexp object and use regexp.test! – Warty Commented Apr 19, 2010 at 18:35
  • It's defined in the ECMAScript spec to behave like this, it'll be the same in all browsers. – bobince Commented Apr 19, 2010 at 18:38
  • Stops if you don't use /g Edit: Ah, answer says why ;) – Darien Commented Apr 19, 2010 at 18:39
Add a ment  | 

1 Answer 1

Reset to default 11

/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)

  1. 暂无评论