Regex Not Matching Dates in DD-MM-YYYY Format with Optional Time in C#
I'm updating my dependencies and I'm dealing with This might be a silly question, but I've been banging my head against this for hours. I'm trying to validate and extract dates in the format of DD-MM-YYYY, with an optional time component (HH:MM) using C#. However, my regex seems to be failing for certain inputs, particularly when the time is not provided or when invalid dates are included. Hereβs the regex Iβm currently using: ```csharp string pattern = "^(\d{2})-(\d{2})-(\d{4})( \d{2}:\d{2})?$"; ``` With this pattern, I attempt to capture the day, month, year, and optionally the hour and minute. Iβve tested it with inputs like `25-12-2020` and `25-12-2020 15:30`, which work fine. However, it fails for inputs like `32-01-2020` (invalid date) or `31-04-2020 14:15` (April has only 30 days), where I expect it to unexpected result validation but it still matches. I also tried to enforce a stricter validation by using more complex logic in my C# code to check the validity of the date after capturing it, but Iβm looking for a way to achieve this directly within the regex itself. Here's how I'm currently checking: ```csharp Match match = Regex.Match(input, pattern); if (match.Success) { DateTime parsedDate; if (!DateTime.TryParseExact(match.Value, "dd-MM-yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate)) { // Handle invalid date } } ``` But this feels like a workaround. Is there a more efficient way to include the date validation directly within the regex? Any suggestions on how to adapt my regex to account for valid date ranges would be greatly appreciated. Am I missing something obvious? I appreciate any insights! Any feedback is welcome!