4

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

Community
  • 1
  • 1
Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88

3 Answers3

19

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)$
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • This regex fails to match 20:30:30 because the value of `20` at HH is considered invalid. – theftprevention Sep 16 '14 at 16:16
  • Another one that works: `^((?=(?:\D*\d\D*){6})(?:[01]\d|2[0-3]):(?:[0-5]\d):(?:[0-5]\d))$` [DEMO](http://regex101.com/r/vK9vM2/3) – RevanProdigalKnight Sep 16 '14 at 16:20
  • 1
    @theftprevention Not sure if the author edited their answer but you can see in the demo that "20:30:30" matches just fine. Can you confirm the issue? Thanks! – Joshua Pinter Feb 06 '20 at 19:38
  • 1
    @JoshuaPinter The answer may have been edited, or I may have been wrong! Either way, my comment is no longer relevant. This was almost six years ago; time flies when you're parsing it with regex! – theftprevention Feb 13 '20 at 20:14
  • @theftprevention LOL. Well played sir! – Joshua Pinter Feb 14 '20 at 19:56
  • Coming back to this, this also matches Strings that may contain 24-hour times but are not exclusively 24-hour times, like "2020-05-29 20:30:30 -0600". How do we ignore these lines so that only Strings with 24-hour times are matched. So it only matches "20:30:30" and not "2020-05-29 20:30:30 -0600"? – Joshua Pinter Jun 01 '20 at 17:05
  • Just need to add a `^` to the start of the pattern and a `$` to the end of the pattern to signify the start and end of the String _only_. I updated the answer with this version as well in case anybody else needs it. – Joshua Pinter Jun 01 '20 at 17:20
10

Give this a try:

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

Demo available here.

theftprevention
  • 5,083
  • 3
  • 18
  • 31
1

The pattern you want is:

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

which is for HH:MM:SS 24 hour format.

void
  • 7,760
  • 3
  • 25
  • 43