0

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.

  • Welcome to SO. You might find reading the site [help section](https://stackoverflow.com/help) useful when it comes to [asking a good question](https://stackoverflow.com/help/how-to-ask). To get the best answers to your question we like to see that you've attempted to solve the problem yourself first using a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Here's a [question checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) you might find useful... – Mister Jojo Jun 30 '21 at 00:32

2 Answers2

2

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

spender
  • 117,338
  • 33
  • 229
  • 351
  • thanks for comments. this also allows, `02:10AM` as valid, but valid needs to be, `02:10 AM` (with a space). I am not sure which expression needs to be added for one space. – user16346412 Jun 30 '21 at 00:34
  • 1
    @user16346412 So, I've just explained how to make an optional quantifier go away. There's only one left in the expression. Can you spot it? – spender Jun 30 '21 at 00:37
  • :) Thanks @Spender, looks like, this is able to work, just removed `?` as spotted above, so expression like, `((1[0-2]|0[1-9]):([0-5][0-9]) ([AP]M))` – user16346412 Jun 30 '21 at 00:39
  • 1
    Why did you include `?` in the first place if you clearly want the space to be mandatory? – Hao Wu Jun 30 '21 at 00:40
  • I found this expression from some post and then played around and filtered out close to my need. But was not sure exactly on how it decodes. And missed that. Thanks for all comments. – user16346412 Jun 30 '21 at 00:44
0

You can use regex demo

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

enter image description here

DecPK
  • 24,537
  • 6
  • 26
  • 42