Gmail Calendar Documents Reader Web more »
Recently Visited Groups | Help | Sign in
Google Groups Home
Message from discussion Irregularities in Regular Expressions
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
 
From:
To:
Cc:
Followup To:
Add Cc | Add Followup-to | Edit Subject
Subject:
Validation:
For verification purposes please type the characters you see in the picture below or the numbers you hear by clicking the accessibility icon. Listen and type the numbers you hear
 
Richard Cornford  
View profile  
 More options Aug 20, 3:56 am
Newsgroups: comp.lang.javascript
From: "Richard Cornford" <Rich...@litotes.demon.co.uk>
Date: Thu, 20 Aug 2009 08:56:00 +0100
Subject: Re: Irregularities in Regular Expressions
Malcolm Dew-Jones wrote:
> Brantley Harris wrote:
> : 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?

> This part is easy.  What you show below is that each /g test
> alternates true and false, so "r.test('\\') == r.test('\\');
> " is true==false, which is certainly false.

> So the only question is why r.test('\\') alternates true and false.

<snip>

Regular expression objects have a - lastIndex - property that receives
different handling depending on whether the regular expression has its -
global - flag set to true or false.  With the - global - flag set to
true the regular expression's - exec - method (which is employed by
its - test - method) does not re-set the - lastIndex - to zero unless it
is already greater than the length of the string being tested. The -
lastIndex - property is used to determine the point in the tested string
at which a test starts. Thus - exec - starts testing the second time
after the point at which the match was found in the first test. That
second test fails, leaving the - lastIndex - greater than the length of
the tested string, so a third test sees the - lastIndex - re-set it to
zero. The result is oscillating behaviour described.

This characteristic allows for constructs such as applying a global
regular expression in the condition of a - while - loop and handling
each match in the body of the loop, and so can be useful. It becomes
problematic when the - global - flag is employed inappropriately, though
it is trivial to manually set/re-set the regular expression's -
lastIndex - property to zero prior to using it.

Richard.


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.

Create a group - Google Groups - Google Home - Terms of Service - Privacy Policy
©2009 Google