user1479571
user1479571

Reputation: 97

date regex which validates 3 different formats

I need a regex for date string which validates

YYYY:MM:DD:HH   
YYYY:MM:DD:HH:mm    
YYYY:MM:DD:HH:mm:ss 

means all 3 formats are valid. Can someone help me with this ?

I have

These 3 regex and needs to be combine in one

Upvotes: 1

Views: 792

Answers (3)

Ro Yo Mi
Ro Yo Mi

Reputation: 15000

I kept your year month day expression d\d\d\d:(0\d|1[012]):([012]\d|3[01]):([01]\d|2[0-3]). Since your hour and minute expressions where the same :[0-5]\d I just required them to appear zero, once or twice with.

The resulting expression is:

^\d\d\d\d:(0\d|1[012]):([012]\d|3[01]):([01]\d|2[0-3])(:[0-5]\d){0,2}$

enter image description here

This expression by francis-gagnon is a slight modification to prevent edge cases where the day or month is expressed as 00.

^\d\d\d\d:(0[1-9]|1[012]):(0[1-9]|[12]\d|3[01]):([01]\d|2[0-3])(:[0-5]\d){0,2}$

enter image description here

If you're looking to also check the date is valid then you could use something like this monster which will test each date position to it's valid and that the time will fit into 24 hour clock:

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

enter image description here

Upvotes: 1

hostmaster
hostmaster

Reputation: 2150

\d{4}:[0-1][0-9]:[0-3][0-9](?::[0-5][0-9](?::[0-5][0-9])?)?

Upvotes: 0

shift66
shift66

Reputation: 11958

this is your pattern

YYYY:MM:DD:HH(:mm(:ss)?)?

? means 0 or 1 time

you can test it here

Upvotes: 1

Related Questions