4

I'm trying to match dates of type:ddmmyyyy , like: 04072001 So far I have this:

^(?:(?:31(?:0?[13578]|1[02]))\1|(?:(?:29|30)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:290?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

which is almost the same as here but without the delimiters( (\/|-|\.) )

Community
  • 1
  • 1
dimzak
  • 2,511
  • 8
  • 38
  • 51
  • So why not just remove `(\/|-|\.)` from the answer to that other question? What doesn't work? – elixenide Jan 14 '14 at 22:43
  • I can't match the example above(tried it in regexpal and while the answer in the link works fine for dd/mm/yyyy, when I remove (\/|-|\.), it stills doesn't match – dimzak Jan 14 '14 at 22:51

3 Answers3

6

You could use something more simple like this:

^(0[1-9]|[1-2][0-9]|31(?!(?:0[2469]|11))|30(?!02))(0[1-9]|1[0-2])([12]\d{3})$

It captures the day, month, year, and validates everything except for whether Feb. 29 is actually a leap year. (To do that, I'd just perform the math on the captured year/date afterwards rather than trying to write it into the expression).

Working example: http://regex101.com/r/dH8mG3

Explained:

- Capture the day: 01-29
    - OR 31, if not succeeded by 02, 04, 06, 09, or 11
    - OR 30, if not succeeded by 02

- Capture the month: 01-12
- Capture the year: 1000-2999 (you could narrow this down 
                               by using number ranges like
                               (1[8-9]\d{2}|20\d{2}) == 1800-2099
brandonscript
  • 68,675
  • 32
  • 163
  • 220
0

A regular expression is not the best tool for this job.

If at all possible, just match ^\d{8}$ (or ^\d\d\d\d\d\d\d\d$ if your regexp engine doesn't support the {8} syntax) and then programmatically check that the date is valid.

In a bit more detail:

  1. Match ^(\d\d)(\d\d)(\d\d\d\d)$ (adjust syntax as needed).
  2. Extract the three matching groups and programmatically check that they constitute a valid date.

The latter requires (a) knowing the number of days in each month, and (b) knowing which years are leap years (which depends on which calendar you're using; Gregorian is the obvious choice, but think about years before it was introduced).

The resulting code will be much easier to read and maintain.

(Also, if you have any control over the format, consider using YYYYMMDD rather than DDMMYYYY; it sorts correctly and it's one of the formats specified by the ISO 8601 standard.)

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
0

Do not validate dates using only RegEx. Your language probably has a built in date object with its own methods and such which you can use in conjunction with your input whose format you've validated with RegEx.

tenub
  • 3,386
  • 1
  • 16
  • 25