1

我需要一个 javascript 中的正则表达式来检查输入是否为 4 位长且介于 2 个有效年份之间。

例如:在 1930 - 2012 之间有可能吗?

4

3 回答 3

3

参考来自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
于 2012-12-28T16:40:05.690 回答
0
/^(19[3-9]\d|20(0\d|1[0-2]))$/
于 2012-12-28T15:47:59.833 回答
0

你可以尝试这样的事情:(\b(19[3-9][0-9]|200[0-9]|201[0-2])\b取自这里)。话虽如此,在处理数字时应该使用数字运算符。使用正则表达式执行此操作会很快变得非常混乱。

于 2012-12-28T09:56:00.047 回答