0

I am saving time in a sheet which can store values between 00:00 to 23:59 and 0000 to 2359. However the regex i have used is not working. Any value which is less the 10:00 hours, e.g., 9:00 it does not work. I realized that its buggy and not upto the mark can anyone help with a proper regex or fix this one:

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

Note i need to be able to enter values without colon as well.

Michal Brašna
  • 2,293
  • 13
  • 17
Expert Novice
  • 1,943
  • 4
  • 22
  • 47

4 Answers4

1

The best I can come up with that seems to match your own attempt is something like this:

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

Regular expression visualization

Debuggex Demo

It seems you want to allow both a single and a double digit entry (counting as minutes i guess, since double digits allowed are 00 to 59) which Michal's answer doesn't take into account. But Anirudh's solution may be the best one. But that depends on your needs I guess.

Regards

SamWhan
  • 8,296
  • 1
  • 18
  • 45
0

Dont use regex..You can use TimeSpan

TimeSpan.ParseExact(input,"hh:mm",CultureInfo.CurrentCulture);

Throws exception if input is not in hh:mm format


Though in your regex you are missing [0-9](:\d{1,2})?

Anirudha
  • 32,393
  • 7
  • 68
  • 89
0

You can modify answer from Regular expression for matching HH:MM time format to

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

Which looks like this

Regexp to match the datetime

Community
  • 1
  • 1
Michal Brašna
  • 2,293
  • 13
  • 17
0

You may try this one :

([0-2][0-3]:[0-5][0-9])|([0-1][0-9]:[0-9][0-9])|(^[0-9]:[0-9]+)
Nagaraj S
  • 13,316
  • 6
  • 32
  • 53
rps
  • 1