Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for hour, minute and second format HH:MM:SS

Tags:

regex

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

07:15:30

But I can't get it work

Right now Im using:

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

Any clue?

like image 668
VAAA Avatar asked Jun 22 '14 03:06

VAAA


1 Answers

^(?:([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

Used some expressions from the regex cheat sheet here:

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

EDIT #1

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

Removed the ? on the SS to make it return false if only 1 digit is entered for seconds.

EDIT #2

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

Changed the HH part a little so if the user types just HH without the MM and SS, it returns false.

EDIT #3

Thanks to this comment for this expression to add to this list

^((?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$)
like image 125
imbondbaby Avatar answered Sep 21 '22 05:09

imbondbaby