2

I'm trying to match a string using regex (of which I am new to) but I can't get it to match.

These should be accepted:

  • GT-00-TRE
  • KK-10-HUH
  • JU-05-OPR

These should not:

  • HTH-00-AS
  • HM-99-ASD
  • NM-05-AK

So the pattern goes 2 letters, hyphen, 2 digits (between 00 and 11 inclusive), hyphen, 3 letters.

So far the best I can come up with is:

var thePattern = /^[a-z]{2}[-][00-11][-][a-z]{3}$/gi;

I can't help but feel that I'm pretty close.

Can anyone give me any pointers?

Thanks.

4

2 回答 2

5

这应该是您需要的:

var thePattern = /^[a-z]{2}[-](0\d|1[0-1])[-][a-z]{3}$/gi;

为了执行 00-11 的范围,您必须说“(0 后跟 0-9)或(1 后跟 0 或 1)”。这是因为指定范围内[]仅适用于单个数字。幸运的是,您的案例非常简单,否则解决此问题可能会变得非常复杂。

于 2012-10-25T14:41:00.947 回答
1

你的正则表达式没问题,但有一件事:数字匹配有点复杂

(0\d|10|11)

您想匹配一个零,后跟一个数字 ( \d) 或 ( |) 一个十或一个十一。

方括号中的内容仅表示范围内的单个字符。[0-5]表示 0 到 5 之间的任何单个数字,[a-q]表示从 a 到 q 的任何小写字母。没有这样的事情,[00-11]因为它需要一次处理多个角色。

于 2012-10-25T14:42:40.023 回答