1

I am trying to compose a regExp that accepts HH:mm time formats, but also accepts all of the intermediate values:

e.g. all of these are accepted:

0
1
12
12:
12:3
12:30
1:
1:3
1:30

For now, I came up with this: ^([\d]{1,2}):?([\d]{1,2})?$

But this accepts any numeric 1/2 digit values for hours and minutes (e.g. 25:66 is acceptable)

So I came relatively close to my goal, but I need to filter out values x>24 from the hours, and x>60 from the minutes?

Michael Vigato
  • 326
  • 2
  • 11
  • 1
    Perhaps like this https://stackoverflow.com/questions/1494671/regular-expression-for-matching-time-in-military-24-hour-format – The fourth bird Jun 18 '21 at 14:06
  • 2
    probably, you can build a regex pattern for your requirement. But, regex is not a good tool if you need to do math-calc. I suggest splitting the input by `:` and check the hour and minutes. It would be a lot easier. – Kent Jun 18 '21 at 14:07

2 Answers2

3

Try this:

^((?:[01][0-9]?)|(?:2[0-4]?)|(?:[3-9]))(?::((?:[0-5][0-9]?)|(?:60))|:)?$

NOTE:

This accepts 24 for HH and 60 for MM as stated in your question:

but I need to filter out values x>24 from the hours, and x>60 from the minutes?

Thus ff. are accepted:

0
1
12
12:
12:3
12:30
1:
1:3
1:30
1:60
24:60
24:00
00:60

and below are not accepted:

25:30
00:61

Regex DEMO 1

If you want to exclude 24 HH and 60 MM, try this instead:

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

Regex DEMO 2

Groups (applies to both cases):

  • \1 = HH
  • \2 = MM
xGeo
  • 2,149
  • 2
  • 18
  • 39
2

You are looking for

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

See the regex demo and the regex graph:

enter image description here

Details:

  • ^ - start of string
  • (?:[01]\d?|2[0-3]?) - either a 0 or 1 followed by an optional digit, or a 2 followed with an optional 0, 1, 2 or 3
  • (?::(?:[0-5]\d?)?)? - an optional sequence of patterns:
    • : - a colon
    • (?:[0-5]\d?)? - an optional sequence of patterns:
      • [0-5] - a digit from 1 to 5
      • \d? - an optional digit
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563