CodexBloom - Programming Q&A Platform

Regex to Validate Date Strings in YYYY-MM-DD Format - Handling Edge Cases with Leap Years

šŸ‘€ Views: 63 šŸ’¬ Answers: 1 šŸ“… Created: 2025-08-06
regex python date-validation Python

I'm trying to debug I'm trying to validate date strings to ensure they follow the YYYY-MM-DD format, including handling leap years correctly. I initially wrote a regex pattern that looks like this: ```regex ^(\d{4})-(\d{2})-(\d{2})$ ``` This captures the general format, but I need to ensure that February 29 is only valid in leap years. My current approach fails for dates like '2021-02-29' and '2023-02-29', which should not be valid. I've considered extending the regex to check the month and day ranges, but that seems overly complex and hard to maintain. My initial testing has shown that simple regex checks like this: ```python import re def is_valid_date(date_str): pattern = r'^(\d{4})-(\d{2})-(\d{2})$' return re.match(pattern, date_str) is not None ``` ...only confirm the format but not the actual validity of the dates. I'm also working with issues with months having different numbers of days. For example, '2023-04-31' should return false, but my current logic isn't capturing that either. Could someone suggest an improved regex pattern or perhaps a better approach that can handle these date validations while keeping the code clean? Using Python's regex module is fine, and I’d appreciate any recommendations on maintaining readability. I'm using Python 3.8 and the `re` library. Thanks in advance! Any examples would be super helpful. I'm on Windows 11 using the latest version of Python. What's the correct way to implement this?