Regex matches date type: ddmmyyyy

I am trying to match dates like: ddmmyyyy  for example: 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 delimiters ( (\/|-|\.))

+4
source share
3 answers

You can use something simpler:

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

He fixes the day, month, year and checks everything, except that February 29 is actually a leap year. (To do this, I just did the math a captured year / date later, rather than trying to write it into an expression).

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

Explanations:

- 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
+3
source

, RegEx. , , , RegEx.

+2

.

, ^\d{8}$ ( ^\d\d\d\d\d\d\d\d$, regexp {8}), , .

:

  • ^(\d\d)(\d\d)(\d\d\d\d)$ ( ).
  • , .

The latter requires (a) know the number of days in each month and (b) know which years are leap years (which depends on which calendar you use, the Gregorian is an obvious choice, but think about the years 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 is sorted correctly and one of the formats specified in the ISO 8601 standard.)

0
source

All Articles