'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

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



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source