日期验证的正则表达式 - 说明
我在线上网进行日期验证,但没有完全理解正则表达式。任何人都可以解释吗?我很困惑?
,{}
和$
。我们为什么需要它们?日期验证的正则表达式 - 说明
dateReg = /^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/;
^ = beginning of the string
[0,1]? = optional zero, one or comma (the comma is probably an error)
\d{1} = exactly one digit (the {1} is redundant)
\/ = a forward slash
[0-2]? = optional zero, one or two (range character class) followed by any single digit (\d{1})
OR [3] = three (character class redundant here) followed by exactly one zero, one or comma
\/ = forward slash
[1]{1}[9]{1}[9]{1}\d{1} = 199 followed by any digit
OR 2-9 followed by any 3 digits
总的来说,这是一个写得很差的表达。我建议找一个更好的,或使用真正的日期解析器。
?的意思是“零或上述中的一个”
{N}表示“恰好n的上述”
$是字符串的结尾(由于@Andy E)
'{n}'表示*“正好是前面提到的n”*。 '{0,n}'将会是*“达到上述”*的n“。 '$'是字符串的结尾,除非使用'm'开关。 – 2011-03-29 15:02:45
@安迪谢谢!我记得刚刚提交的第一个事实;) – 2011-03-29 15:04:28
?
意思是“零或一个发生“。 {x}
(其中x是一个数字)的意思是“精确的x OCCURENCES” $
的意思是“行结束”
这些都是很基本的正则表达式,我推荐你读some documentation。
简要总结一下:
'?'将匹配您放在它前面的模式组的0或1倍。在这种情况下,它可能被滥用,应该排除在外,但这一切都取决于您想要匹配的内容。
`{x}'告诉正则表达式正好x次匹配前面的模式组。
`$'表示匹配行的末尾。
没关系,我现在看到他们想要匹配什么:'?'这里需要。 – 2011-03-29 15:05:42
好:
^ // start of the text
$ // end of the text
X{n} // number n inside these curly parenthesis define how many exact occurrences of X
X{m,n} // between m to n occurrences of X
X? // 0 or 1 occurrence of X
\d // any digits 0-9
有关的Javascript日期验证详细说明,请参阅:Regular Expression to only grab date
在Javascript中,你可以通过它传递给Date.Parse()函数验证日期。成功转换为日期对象意味着您拥有有效的日期。
不建议使用正则表达式。边缘案例太多,代码难以维护。
你从哪里得到的?这是我见过的最糟糕的正则表达式之一。 – 2011-03-29 15:13:35