0

I have regex for time /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/

This validates 24-hr format as well.

What should be the regex if I do not want to accept leading zeroes?

Example:

9:31 not 09:31

Update:

This issue: Regular expression for matching HH:MM time format accepts both with leading and without leading zeroes. But I'm looking for a 24-hr regex that DOES NOT ACCEPT LEADING ZEROES. It's not a duplicate

I tried this:

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

but doesn't accept 0:24

Any ideas? Thank you

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Char
  • 2,073
  • 8
  • 28
  • 45

2 Answers2

2

The second alternation in the capture group matches hours with a leading zero:

0[0-9]

So, just remove that. You can also make the pattern more DRY by using 1? instead of the first two alternations, and \d instead of [0-9], if you want:

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

https://regex101.com/r/jS9TTj/1

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you. Your second suggestion doesn't accept 24-hr format though. I followed your first suggestion and removed the second alteration. – Char Jun 24 '19 at 01:54
  • 1
    See the linked regex101, it looks to work just fine for 24-hour format (just doesn't accept leading zeros, as requested): https://regex101.com/r/jS9TTj/1 – CertainPerformance Jun 24 '19 at 01:54
  • `1?\d` might be more concise, but `\d|1\d` is a little clearer for maintenance sake. :-) – RobG Jun 24 '19 at 02:53
0

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

I was looking for a regex that does not accept leading zero

Examples:

  • 0:30
  • 9:30 (not 09:30)
  • 0:00 (12 midnight)

https://regex101.com/r/hcjjHN/2

Community
  • 1
  • 1
Char
  • 2,073
  • 8
  • 28
  • 45