Michael
Michael

Reputation: 163

YYYY/MM/DD date format regular expression

I want to use regular expression for matching these date formats as below in C#.

  1. YYYY/MM/DD 2013/11/12
  2. YYYY/M/DD 2013/5/11
  3. YYYY/MM/D 2013/10/5
  4. YYYY/M/D 2013/5/6

I have tried some regular expressions but they can't match the 4 date formats. such as

^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])

Upvotes: 0

Views: 28557

Answers (6)

Ajit
Ajit

Reputation: 1

((([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 the regex for yyyy-MM-dd format.

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

Tested working perfect..

Upvotes: 0

Gowtham K
Gowtham K

Reputation: 1

Try this. This accepts all four patterns

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

Upvotes: -1

Ahmed Wahbi
Ahmed Wahbi

Reputation: 128

Ajit's regex is nearer to perfect but leaks the evaluation of the leap years that end with 12 and 16. Here is the correction to 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])))

Upvotes: 0

bansi
bansi

Reputation: 56982

You may need more than that to match date. Try this:

(19|20)\d\d([-/.])(0?[1-9]|1[012])\2(0?[1-9]|[12][0-9]|3[01])

Upvotes: 0

gwillie
gwillie

Reputation: 1899

check this to get an idea of the compexity of regex and validating dates. so i would use

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

then in c# do whatever to validate the match. while it can be done, you'll be spending a lot of time trying to achieve it, though there is a regex in that post that with a bit of fiddling supposedly will validate dates in regex, but it is a scary looking regex

Upvotes: 4

cxw
cxw

Reputation: 17041

Try

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

The curly braces {} give the number allowed. E.g., \d{1,2} means either one or two digits.

Upvotes: 3

Related Questions