views:

100

answers:

3

Hello gurus,

I have a javascript function that looks element id with certain patterns. So I have the following script:

if (f.elements[i].id.match(/DataList\[-\d{3}|\d{3}\]\.MemberId/)) {
  //do something
}

It should match elements with ids such as these:

DataList[-1].MemberId
DataList[-2].MemberId

And it does, however it also matches the following:

DataList[-1].FirstName
DataList[-2].FirstName

which I don't want.

Could any guru take a look at the regular expression above and point out what is going wrong?

Thanks,

Cullen

+2  A: 

Try to anchor your regex at the beginning with a ^ and at the end with a $, group your digit match and allow 1-3 digits instead of just 3.

if (f.elements[i].id.match(/^DataList\[(-\d{1,3}|\d{1,3})\]\.MemberId$/)) {
  //do something
}

The way you had it, it was matching anything containing "DataList[-123" or containing "123].MemberId".

A simpler overall regex that accomplishes the same thing is:

if (f.elements[i].id.match(/^DataList\[-?\d{1,3}\]\.MemberId$/)) {
  //do something
}
Asaph
thanks Asaph. I'm using the first solution.
Cullen Tsering
+2  A: 

The or is saying:

DataList\[-\d{3} OR \d{3}\]\.MemberId/

This regex matches correctly:

DataList\[-?\d{1,3}\]\.MemberId
Macarse
thanks Macarse, this is the source of the problem.
Cullen Tsering
+1  A: 

My suggestion

   if (f.elements[i].id.match(/DataList\[-[0-9]{1,3}\]\.MemberId/)) {
  }

The {} determines how many #s you want to support so 1-3 would match upu to [999]

Cranium Slows