YYYY / MM / DD Date Format Regular Expression

I want to use a regex to match these date formats, as shown below in C #.

  • YYYY / MM / DD 2013/11/12
  • YYYY / M / DD 2013/5/11
  • YYYY / MM / D 2013/10/5
  • YYYY / M / D 2013/5/6

I tried some regular expressions, but they cannot match 4 date formats. such as

^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01]) 
0
c # regex
source share
6 answers

check this one to get an idea of ​​the complexity of regular expressions and validation dates. so i would use

 \d{4}(?:/\d{1,2}){2} 

then in C # do everything to check compliance. while this can be done, you will spend a lot of time trying to achieve this, although there is a regular expression in this post that with a bit of fiddling will supposedly check dates in regex, but it is a scary looking regular expression

+3
source share

Try

 ^\d{4}[-/.]\d{1,2}[-/.]\d{1,2}$ 

The curly braces {} indicate a valid number. For example, \d{1,2} means one or two digits.

+2
source share

You may need more to match the date. Try the following:

 (19|20)\d\d([-/.])(0?[1-9]|1[012])\2(0?[1-9]|[12][0-9]|3[01]) 
0
source share
 ((([0-9][0-9][0-9][1-9])|([1-9][0-9][0-9][0-9])|([0-9][1-9][0-9][0-9])|([0-9][0-9][1-9][0-9]))\-((0[13578])|(1[02]))\-((0[1-9])|([12][0-9])|(3[01])))|((([0-9][0-9][0-9][1-9])|([1-9][0-9][0-9][0-9])|([0-9][1-9][0-9][0-9])|([0-9][0-9][1-9][0-9]))\-((0[469])|11)\-((0[1-9])|([12][0-9])|(30)))|(((000[48])|([0-9][0-9](([13579][26])|([2468][048])))|([0-9][1-9][02468][048])|([1-9][0-9][02468][048]))\-02\-((0[1-9])|([12][0-9])))|((([0-9][0-9][0-9][1-9])|([1-9][0-9][0-9][0-9])|([0-9][1-9][0-9][0-9])|([0-9][0-9][1-9][0-9]))\-02\-((0[1-9])|([1][0-9])|([2][0-8]))) 

This is a regular expression for the yyyy-MM-dd format.

You can replace - with \/ for yyyy/MM/dd ...

Tested works great.

0
source share

Ajit regex is closer to perfection, but leaks of leap years ending in 12 and 16 are leaked. Here is a fix that would be just perfect

 ((([0-9][0-9][0-9][1-9])|([1-9][0-9][0-9][0-9])|([0-9][1-9][0-9][0-9])|([0-9][0-9][1-9][0-9]))-((0[13578])|(1[02]))-((0[1-9])|([12][0-9])|(3[01])))|((([0-9][0-9][0-9][1-9])|([1-9][0-9][0-9][0-9])|([0-9][1-9][0-9][0-9])|([0-9][0-9][1-9][0-9]))-((0[469])|11)-((0[1-9])|([12][0-9])|(30)))|(((000[48])|([0-9]0-9)|([0-9][1-9][02468][048])|([1-9][0-9][02468][048])|([0-9]0-9)|([0-9][1-9][13579][26])|([1-9][0-9][13579][26]))-02-((0[1-9])|([12][0-9])))|((([0-9][0-9][0-9][1-9])|([1-9][0-9][0-9][0-9])|([0-9][1-9][0-9][0-9])|([0-9][0-9][1-9][0-9]))-02-((0[1-9])|([1][0-9])|([2][0-8]))) 
0
source share

Try it. It accepts all four patterns.

 @"\d{4}[- /.]([1-9]|0[1-9]|1[012])[- /.]([1-9]|0[1-9]|[12][0-9]|3[01])" 
-one
source share

All Articles