Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern for EXACTLY HH:MM:SS time String

I want to validate sting time format in EXACTLY hh:mm:ss String.
I mean by EXACTLY that
Each of hours / minutes / seconds MUST be 2 digits
Also Accept only logical values like

  • hours [ from 00 to 23 ]
  • minutes [ from 00 to 59 ]
  • seconds [ from 00 to 59 ]

When i checked Regex pattern for HH:MM:SS time string
The answer accept hh:mm:ss string but also accepts cases like 2:3:24

Thanks in advance

like image 338
ahmednabil88 Avatar asked Nov 27 '22 09:11

ahmednabil88


1 Answers

Your regex would be,

(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)

This will match both "20:30:30" and "2020-05-29 20:30:30 -0600".

DEMO

If you want to only match Strings that are exclusively 24-hour times, use the following:

^(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)$

This will match only "20:30:30" and not "2020-05-29 20:30:30 -0600".

DEMO

Java regex would be,

(?:[01]\\d|2[0123]):(?:[012345]\\d):(?:[012345]\\d)

And for exclusively 24-hour Strings,

^(?:[01]\\d|2[0123]):(?:[012345]\\d):(?:[012345]\\d)$
like image 122
Avinash Raj Avatar answered Dec 05 '22 17:12

Avinash Raj