Regular expression for hour, minute and second format HH: MM: SS

Im trying to implement Regex for HH: MM: SS, example:

07:15:30

But I can't make it work

Now I am using:

([01]?[0-9]|2[0-3]):[0-5][0-9]

Any clue?

+4
source share
1 answer
^(?:([01]?\d|2[0-3]):([0-5]?\d):)?([0-5]?\d)$

Explanation:

^                   #  Start of string
(?:                 #  Try to match
([01]?\d|2[0-3]):   #  HH:
([0-5]?\d):         #  MM:
)?                  #  (entire group)
([0-5]?\d)          #  SS
$                   #  End of string

Some expressions from the regex cover are used here:

http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

EDIT NO. 1

^(?:([01]?\d|2[0-3]):([0-5]?\d):)?([0-5]\d)$

Deleted ?to SSto return false if only one digit is entered within a few seconds.

EDIT No. 2

^([0-5]\d):([0-5]\d):([0-5]\d)$

The part has changed a bit HH, so if the user enters only HHwithout MMand SS, he returns false.

EDIT No. 3

comment

^((?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$)
+11

Source: https://habr.com/ru/post/1545526/


All Articles