Search code examples
regexdatetime-parsingtime-format

Regex for hours, min and optionally Section with more possible formats


I need to create regex that allows below time values: single digit or double digits and optionally second.

All possible combination for single digit of Hour/Minute/Second:

hh:mm:ss AM/PM
h:m:s AM/PM
hh:m:s AM/PM
h:mm:s AM/PM
h:m:ss

Accepted values are:

11:12:59 AM
1:2:3 PM
1:22:30 pm
01:2:00 PM
1:3 PM

I tried some possible combination from, https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s06.html like:

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

But it doesn't work as expected above.

Can you please correct me on above sample or some other regex that allows above possible values.


Solution

  • The regex in the question doesn't make the am/pm optional.
    And the minutes/seconds can be 1 group that occurs 1 to 2 times.

    ^(?:[01]?[0-9]|2[0-3])(?:[:][0-5]?[0-9]){1,2}(?:[ ][APap][Mm])?$
    

    Test on regex101 here