Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading