Regex Not Matching Date Formats with Optional Time in Python - implementing Variations
I'm performance testing and I'm sure I'm missing something obvious here, but I'm stuck on something that should probably be simple. Quick question that's been bugging me - I'm trying to construct a regex pattern in Python to match date strings that may or may not include a time component... My requirement is to match dates in the format `YYYY-MM-DD` and optionally followed by a time in `HH:MM:SS`. For example, both `2023-10-10` and `2023-10-10 14:30:00` should be matched. However, I'm working with issues where my pattern seems to be overly restrictive and fails to match valid inputs. Here's the regex pattern I've been using: ```python import re date_pattern = r'^(\d{4}-\d{2}-\d{2})(\s+(\d{2}:\d{2}:\d{2}))?$' text1 = '2023-10-10' text2 = '2023-10-10 14:30:00' matches1 = re.match(date_pattern, text1) matches2 = re.match(date_pattern, text2) print(matches1 is not None) # Should be True print(matches2 is not None) # Should be True ``` However, when I run this code, I get `False` for the first test case, even though it should match. I suspect it's an scenario with the optional group, but I need to seem to identify the question. I've also verified that I'm using Python 3.9.1. Can anyone guide to adjust the regex to correctly capture both formats? I'm working on a application that needs to handle this. Is there a better approach? Any examples would be super helpful. For reference, this is a production application. This is for a microservice running on CentOS. Is there a simpler solution I'm overlooking?