Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

regex - 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 = /.*?bl.*gr.*/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:

> /.*?bl.*gr.*/gi.test("Blue-Green");
true
> /.*?bl.*gr.*/gi.test("Blue-Green");
true
> /.*?bl.*gr.*/gi.test("Blue-Green");
true
> /.*?bl.*gr.*/gi.test("Blue-Green");
true

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...