Irregularities in Regular Expressions

B

Brantley Harris

Type this into your javascript console, you'll notice it prints out
false.
r = new RegExp("\\\\", "g"); r.test('\\') == r.test('\\');

What is going on here?

Without the global flag it will print true, as expected:
r = new RegExp("\\\\"); r.test('\\') == r.test('\\');

But with the flag it will alternate:
r = new RegExp("\\\\", "g");
r.test('\\') --> true
r.test('\\') --> false
r.test('\\') --> true

I have tried this in both Firefox and Safari. Am I going insane? Can
anyone explain this?
 
T

Thomas 'PointedEars' Lahn

Brantley said:
Type this into your javascript console,

The term "javascript console" would normally need to be defined by an OP as
there is not only one ECMAScript implementation named "javascript", and
behavior may and is known to vary between implementations; especially with
RegExp objects.
you'll notice it prints out false.
r = new RegExp("\\\\", "g"); r.test('\\') == r.test('\\');

What is going on here?

Without the global flag it will print true, as expected:
r = new RegExp("\\\\"); r.test('\\') == r.test('\\');

But with the flag it will alternate:
r = new RegExp("\\\\", "g");
r.test('\\') --> true
r.test('\\') --> false
r.test('\\') --> true

I have tried this in both Firefox and Safari. Am I going insane?

Hopefully not.
Can anyone explain this?

Yes.

Your Regular Expression, that the RegExp object referred to by `r'
encapsulates, matches one literal backslash. There is only one backslash in
the string to be tested each (the first and only argument of the test()
call, respectively), and you are reusing the same RegExp object, which has
its global property set to `true' per the constructor call.

As RegExp.prototype.test() calls RegExp.prototype.exec() and that must
return `null' if there are no more matches and the `global' property has the
value `true' (step 6 of its specified algorithm)¹, the first call to
r.test() returns `true', but the second one returns `false'².

See the ECMAScript Language Specification, Edition 3 Final:

| 15.10.6.3 RegExp.prototype.test(string)
|
| Equivalent to the expression RegExp.prototype.exec(string) != null.

And `(true == false)' results in `false' (section 11.9.1).


PointedEars
___________
¹ If that were not so, the useful loop `while ((m = /x/g.exec(s)))' would
never terminate in implementations of said ECMAScript Edition.
² Consequently, the next call would return `true' again as the lastIndex
value would be reset to 0 and there would be a match at index 0.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top