Sree
Sree

Reputation: 2922

Regex for only hours or hours and minutes

I am using regex ^(([0-9])|([0-1][0-9])|([2][0-3])):(([0-9])|([0-5][0-9]))$ for time. It is very good regex but when user wants to enter only hours like 8 or 12 without colon and minutes it is not allowing. Can any one suggests which regular expressions suits hours only or hours:minutes.

Upvotes: 2

Views: 4789

Answers (2)

Hans Kesting
Hans Kesting

Reputation: 39283

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

made the ":mm" part optional by putting it in () and adding a ? quantifier.


An explanation as generated by https://www.regexplained.co.uk/

Regex description

First group (labeled as "group #4"):

  • A single digit (0..9), or
  • A '0' or '1', followed by a single digit (00..19), or
  • A '2', followed by a 0, 1, 2 or 3 (20..23)

Then an optional second group (labeled as "group #8")

  • A colon (':'), followed by
  • Either a single digit (0..9), or
  • A 0..5 followed by a single digit (00..59)

Upvotes: 4

Keppil
Keppil

Reputation: 46219

Just make the last part optional, like this:

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

Upvotes: 1

Related Questions