Correct Regular expressions to match a date

后端 未结 11 644
不知归路
不知归路 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:34

    OK, a regex that will validate month and day ranges could be

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

    If you want to restrict the years, say, from 1900 to 2050, you could end up with

    (?:2050|20[0-4][0-9]|19[0-9]{2})-(?:1[0-2]|[1-9])-(?:3[01]|[12][0-9]|[1-9])
    

    They will not catch "subtly wrong" dates like February 31st, so it's really quite clear that a sanity check needs to be performed outside of the regex.

提交回复
热议问题