Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match date of type: ddmmyyyy

Tags:

regex

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( (\/|-|\.) )

like image 488
dimzak Avatar asked Mar 20 '23 23:03

dimzak


1 Answers

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
like image 155
brandonscript Avatar answered Apr 06 '23 09:04

brandonscript