0

I've looked at a few regex time questions but haven't found one that I need and I'm pretty clueless on how to write regex expressions.

I need time values like this to pass:

  • 06:03:05 AM
  • 06:03 pm
  • 6:3:5 AM

This regex seems like it'd work for this(which I found on Here but I also need to have the AM/PM part required but it can also be case insensitive.

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

So to sum up what I need in this regex:

  • single digit h:m:s acceptable
  • double digit hh:mm:ss acceptable
  • AM/PM required but case insensitive
  • if the AM/PM part can be entered as a or p would be nice, but not needed
  • seconds are optional
  • 24 hour time not acceptable

Any help would be greatly appreciated.

Community
  • 1
  • 1
D.Galvez
  • 99
  • 2
  • 10

2 Answers2

2

The regex you provide supports 24 hour time, the following my stringently follows your request

(1[012]|0?\d):[0-5]?\d(:[0-5]?\d)?\s+[AaPp][Mm]?
zellio
  • 31,308
  • 1
  • 42
  • 61
1

Just add ? after the seconds part and \s+[aApP][mM] at the end of the re:

([0-1]?\d|2[0-3]):([0-5]?\d)(:([0-5]?\d))?\s+[aApP][mM]

And when you don't neet 24h format change the first part:

(1[0-2]|0?\d):([0-5]?\d)(:([0-5]?\d))?\s+[aApP][mM]
Igor Chubin
  • 61,765
  • 13
  • 122
  • 144