Home > Enterprise >  How can I use regex in python to validate dates in the MM/DD/YYYY format?
How can I use regex in python to validate dates in the MM/DD/YYYY format?

Time:02-12

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

CodePudding user response:

(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.

  • Related