简体   繁体   中英

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])

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

Try

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

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

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])
((([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..

Ajit的正则表达式接近完美,但泄漏了以12和16结尾的the年的评估。这是完美的更正

((([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])))

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])"

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