Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for matching time in military (24 hour) format

I would like a JavaScript regular expression that will match time using the 24 hour clock, where the time is given with or without the colon.

For example, I would like to match time in the following formats:

  • 0800
  • 23:45
  • 2345

but that would not match invalid times such as

  • 34:68
  • 5672
like image 219
rswolff Avatar asked Sep 29 '09 20:09

rswolff


People also ask

How does regular expression validate time in 12 hour format?

On a 12-hour clock, if the first digit is 0, the second digit allows all 10 digits, but if the first digit is 1, the second digit must be 0, 1, or 2. In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›.

What is match regular expression?

Match(String) Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor. Match(String, Int32) Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position in the string.

Which regex pattern can be used to find the time?

In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›. On a 24-hour clock, if the first digit is 0 or 1, the second digit allows all 10 digits, but if the first digit is 2, the second digit must be between 0 and 3. In regex syntax, this can be expressed as ‹ 2[0-3]|[01]?[0-9] ›.


1 Answers

This should do it:

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

The expression reads:

^        Start of string (anchor) (        begin capturing group   [01]   a "0" or "1"   \d     any digit  |       or   2[0-3] "2" followed by a character between 0 and 3 inclusive )        end capturing group :?       optional colon (        start capturing   [0-5]  character between 0 and 5   \d     digit )        end group $        end of string anchor 
like image 172
Greg Avatar answered Oct 11 '22 14:10

Greg