Correct Regular expressions to match a date

后端 未结 11 661
不知归路
不知归路 2021-01-27 09:50

What is the correct regular expression to use to validate a date like. 2009-10-22 or 2009-01-01 etc. Platform PHP

11条回答
  •  爱一瞬间的悲伤
    2021-01-27 10:41

    For a complete validation (which would include verifying that the day, month and year parts are valid) a Regex is not the tool of choice. Apart from month issues you'd get into trouble with leap years...

    So, if you just want to check if the rough format is correct, or isolate the different parts (year-month-day), a regex is fine.

    ([0-9]{1,4})-(1[012]|0?[1-9])-([12][0-9]|3[01]|0?[1-9])
    

    This is already pretty exact and captures the year (0..9999), month and day into capture groups, ready for parsing...

提交回复
热议问题