开发者

JavaScript: string.match regular expression help

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 m开发者_Python百科atch 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


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
}


The or is saying:

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

This regex matches correctly:

DataList\[-?\d{1,3}\]\.MemberId


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]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜