简体   繁体   English

用于日期验证的正则表达式-解释

[英]Regular Expression for date validation - Explain

I was surfing online for date validation, but didn't exactly understand the regex. 我正在网上冲浪以进行日期验证,但并不完全了解正则表达式。 Can anyone explain it? 有人可以解释吗? I'm confused with ? 我感到困惑? , {} and $ . {}$ Why do we need them? 我们为什么需要它们?

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}))$/;

? means “zero or one occurences”. 表示“零或一个事件”。
{x} (where x is a number) means “exactly x occurences” {x} (其中x是数字)表示“恰好出现了x次”
$ means “end of line” $表示“行尾”

These are very basic regex, I recommand you to read some documentation . 这些是非常基本的正则表达式,我建议您阅读一些文档

In Javascript you could validate date by passing it to Date.Parse() function. 在Javascript中,您可以通过将日期传递给Date.Parse()函数来验证日期。 Successful conversion to a date object means you have a valid date. 成功转换为日期对象意味着您拥有有效的日期。

Wouldn't recommend using regex for this. 不建议为此使用正则表达式。 Too many edge cases and code gets hard to maintain. 太多的极端情况和代码变得难以维护。

^ = 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

Overall, that's a really poorly written expression. 总体而言,这是一个非常糟糕的表达方式。 I'd suggest finding a better one, or using a real date parser. 我建议找到一个更好的,或使用一个实际的日期解析器。

? means "Zero or one of the aforementioned" 表示“零或上述任何一项”

{n} means "exactly n of the aforementioned" {n}表示“恰好是前述的n个”

$ is the end of the String (Thanks @Andy E) $是字符串的结尾(感谢@Andy E)

To summarize briefly: 简要总结一下:

`?' '?' will match 0 or 1 times the pattern group you put in front of it. 将匹配您放置在其前面的图案组的0或1倍。 In this case, it's possibly being misused and should be left out, but it all depends on just what you want to match. 在这种情况下,可能会滥用它,应该将其排除在外,但这完全取决于您要匹配的内容。

`{x}' tells the regex to match the preceding pattern group exactly x times. “ {x}”告诉正则表达式与前面的模式组精确匹配x次。

`$' means to match the end of the line. $表示匹配行尾。

Well: 好:

^ // 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

For more help about Javascript date validation please see: Regular Expression to only grab date 有关Javascript日期验证的更多帮助,请参见: 仅捕获日期的正则表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM