1

I'm working on a project for my beginning python class and it's heavily focused on regex. Part of this project involves using regex to validate the date format MM/DD/YYYY.

My Regex is as follows:

(?:0?[1-9]|1[0-2])\/(?:0?[1-9]|12\d|3[01])\/(?:1\d{3})

I'm having an issue where if I enter a date like

13/31/1999

my regex wont match the first 1, but instead will match

3/31/1999

I'm not sure why this is happening because I'm expecting if the DD starts with a 1, then my regex should only match that 1 followed by either 0,1,2.

Here is a visual representation of my issue

  • You may want to match the start (`^`) and maybe the end (`$`) of your string. Does that help? – aaossa Feb 11 '22 at 22:21
  • 1
    Thanks for the help. I just needed to add the caret symbol to the start and that fixed my problem. –  Feb 11 '22 at 22:23
  • You may find this of use if you're not forced to use regex: https://stackoverflow.com/q/16870663/2449857 – Jack Deeth Feb 11 '22 at 23:11

1 Answers1

0

(For the record, this was solved in the comments) Add the caret (^) at the beginning of your regular expression to match the beginning of the string. That should match your requirement:

^(?:0?[1-9]|1[0-2])\/(?:0?[1-9]|12\d|3[01])\/(?:1\d{3})

You can see it working with your examples here.

aaossa
  • 3,763
  • 2
  • 21
  • 34