CodexBloom - Programming Q&A Platform

Regex Fails to Validate Custom Time Formats in Python - Handling AM/PM with Optional Seconds

👀 Views: 84 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-03
regex python validation Python

I'm working on a project and hit a roadblock. This might be a silly question, but I'm working on a Python application where I need to validate custom time formats, specifically HH:MM AM/PM with optional seconds (HH:MM:SS AM/PM). I want to ensure that the input adheres strictly to this format but also allows for the seconds to be omitted. My current regex pattern is as follows: ```python import re time_pattern = r'^(0[1-9]|1[0-2]):([0-5][0-9])(:([0-5][0-9]))?\s?(AM|PM)$' # Test examples valid_times = [ '12:30 PM', '01:45:22 AM', '04:59 PM', '07:05:00 AM' ] invalid_times = [ '13:00 PM', '12:60 AM', '03:15 PM:00', '00:00 AM' ] for time in valid_times: if re.match(time_pattern, time): print(f'{time} is valid') else: print(f'{time} is invalid') for time in invalid_times: if re.match(time_pattern, time): print(f'{time} is valid') else: print(f'{time} is invalid') ``` While this works for most cases, I'm encountering some unexpected behavior. The pattern seems to incorrectly validate strings like '12:30:00 PM' as valid when it shouldn't because I'm not handling the case where the seconds are specified without the entire HH:MM:SS format. Additionally, when I test '12:60 PM', it returns invalid as expected, but I want to ensure that my regex is robust against other edge cases, such as leading zeros. I realize that I might need to adjust my regex to handle these scenarios better but I'm not sure how to incorporate optional non-capturing groups effectively. Any guidance on refining this regex or alternative approaches would be greatly appreciated! I'm working on a web app that needs to handle this. Is there a better approach? My development environment is Ubuntu 20.04. What's the best practice here? I'd be grateful for any help.