user16346412
user16346412

Reputation: 3

Trying to create a regex for HH:MM A

Trying to create a regular expression HH:MM A. required two digit for HH and MM and space then Meridien AM/PM - caps only.

Find many answers on other posts but it didn't work exactly. Mostly I used to do with time picker control. But wants to go with regex for current scenario.

((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AP][M]))

above one also allowed, 1:23 AM or 1:23AM. Need only, 01:23 AM allowed. 12 hours format. can you guide on this. It allows leading 0 and space options. Thanks.

Upvotes: 0

Views: 70

Answers (2)

spender
spender

Reputation: 120400

Yes. The second alternative for the first 2 digits allows the 0 to be optional.

Just remove the "zero or one" quantifier ? from the 0 and you'll make it non-optional:

((1[0-2]|0[1-9]):([0-5][0-9]) ?([AP]M))

You can use exactly the same technique to make the optional (space) character non-optional too.

BTW [MM] is equivalent to just M

Upvotes: 2

DecPK
DecPK

Reputation: 25408

You can use regex demo

(?:(?:0[1-9])|(?:1[0-2])):(?:[0-5][0-9]) [AP]M

enter image description here

Upvotes: 0

Related Questions