年x和年y之间的4位数 - javascript正则表达式

时间:2012-12-28 09:46:50

标签: javascript regex

我需要一个javascript中的正则表达式,它将检查输入是4位数长度和2个有效年份之间。

例如:1930年至2012年之间  有可能吗?

3 个答案:

答案 0 :(得分:1)

来自http://utilitymill.com/utility/Regex_For_Range

的参考号
First, break into equal length ranges:
  1930 - 2012

Second, break into ranges that yield simple regexes:
  1930 - 1999
  2000 - 2009
  2010 - 2012

Turn each range into a regex:
  19[3-9][0-9]
  200[0-9]
  201[0-2]

Collapse adjacent powers of 10:
  19[3-9][0-9]
  200[0-9]
  201[0-2]

Combining the regexes above yields:
  (19[3-9][0-9]|200[0-9]|201[0-2])

Next we'll try factoring out common prefixes using a tree:
Parse into tree based on regex prefixes:
  . 1 9 [3-9] [0-9]
    2 0 0 +----
      + 1 [0-2]

Turning the parse tree into a regex yields:
  (19[3-9][0-9]|20(0[0-9]|1[0-2]))

We choose the shorter one as our result.

\b(19[3-9][0-9]|200[0-9]|201[0-2])\b

答案 1 :(得分:0)

您可以尝试这样的事情:\b(19[3-9][0-9]|200[0-9]|201[0-2])\b(摘自here)。话虽这么说,你应该在处理数字时使用数字运算符。使用正则表达式执行此操作可能非常快速。

答案 2 :(得分:0)

/^(19[3-9]\d|20(0\d|1[0-2]))$/