我需要一个 javascript 中的正则表达式来检查输入是否为 4 位长且介于 2 个有效年份之间。
例如:在 1930 - 2012 之间有可能吗?
参考来自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
/^(19[3-9]\d|20(0\d|1[0-2]))$/
你可以尝试这样的事情:(\b(19[3-9][0-9]|200[0-9]|201[0-2])\b
取自这里)。话虽如此,在处理数字时应该使用数字运算符。使用正则表达式执行此操作会很快变得非常混乱。