Home > Software design >  Regex for month matching with format "M/DD/YY Time"
Regex for month matching with format "M/DD/YY Time"

Time:01-04

i am trying to match date as below: "3/21/22 6:00 AM" so this is "M/DD/YY Time"

regex which i am trying to write is:

^((0?[1-9]|1[012])|\d|1\d|2\d|3[01])\/(22) ([1-9]|0[1-9]|1[0-2]):[0-5][0-9] ([AaPp][Mm])$

and it is not catching the first "3" so month is not included. Why? I do not understand this OR statement in Regex "|" in this case. So 1\d 2\d i do not know how this is working

Can you please help Best Michal

CodePudding user response:

In your regex, ((0?[1-9]|1[012])|\d|1\d|2\d|3[01]) matches numbers from 0 to 31. Next comes the \/22 pattern, so this part only allows to numbers in the date part only.

You need to amend the regex to

^(0?[1-9]|1[012])\/([12]?\d|3[01])\/(22) (0?[1-9]|1[0-2]):[0-5]\d ([AaPp][Mm])$
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

See the regex demo.

Details:

  • ^ - start of string
  • (0?[1-9]|1[012]) - Group 1: an optional 0 and then a non-zero digit or 10/11/12
  • \/ - a / char
  • ([12]?\d|3[01]) - Group 2: an optional 1 or 2 and then a digit, or 30/31
  • \/ - a / char
  • (22) - Group 3: 22
  • - space
  • (0?[1-9]|1[0-2]) - Group 4: an optional 0 and then a non-zero digit or 10/11/12
  • : - a colon
  • [0-5]\d - a digit from 0 to 5 and then any one digit.
  • - space
  • ([AaPp][Mm]) - Group 5: am or pm
  • $ - end of string.
  • Related