简体   繁体   中英

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”
$ 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. 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"

$ is the end of the String (Thanks @Andy E)

To summarize briefly:

`?' will match 0 or 1 times the pattern group you put in front of it. 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.

`$' 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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