thefallenchief
thefallenchief

Reputation: 33

RegEx matching HH:MM, HH:MM:SS OR HH:MM:SS.XXX

So far I have the following:

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

This matches (as expected) 23:59, 23:59:30, 23:59:34.123 or 23:59:12.1 Doesn't match 23:60, 23:59. But unfortunately matches 23:59.60 Any ideas how to give the finishing touches?

Upvotes: 2

Views: 1610

Answers (2)

karthik manchala
karthik manchala

Reputation: 13640

You have to change \d{1,3} to \d{3} for resticting milliseconds part to .XXX (exactly three occurrences):

^(([0-1][0-9])|([2][0-3])):([0-5][0-9])(:([0-5][0-9]))?([.]\d{3})?$
                                                              ↑

See DEMO

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

Since milliseconds are allowed only when seconds are present, you should make the optional parts for milliseconds nested inside the optional part for seconds:

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

Demo.

Upvotes: 2

Related Questions