Regex for Date Parsing — ISO 8601, US, and European Formats
Regex patterns for parsing dates in ISO 8601 (YYYY-MM-DD), US (MM/DD/YYYY), and European (DD/MM/YYYY) formats with named capture groups for extraction.
Detailed Explanation
Date Parsing with Regex
Date formats vary widely across locales and systems. Regex can extract and validate date strings, but always be aware of format ambiguity.
ISO 8601 Format (YYYY-MM-DD)
(?<year>\d{4})-(?<month>0[1-9]|1[0-2])-(?<day>0[1-9]|[12]\d|3[01])
This validates:
- Year: any 4 digits
- Month: 01-12
- Day: 01-31
Example matches: 2024-01-15, 2023-12-31
US Format (MM/DD/YYYY)
(?<month>0[1-9]|1[0-2])/(?<day>0[1-9]|[12]\d|3[01])/(?<year>\d{4})
Example matches: 01/15/2024, 12/31/2023
European Format (DD/MM/YYYY or DD.MM.YYYY)
(?<day>0[1-9]|[12]\d|3[01])[/.](?<month>0[1-9]|1[0-2])[/.](?<year>\d{4})
Example matches: 15/01/2024, 31.12.2023
ISO 8601 DateTime
For full datetime including time and timezone:
\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)
Limitations
Regex cannot validate all date logic:
- February 30 will pass the pattern
- Leap year validation requires programmatic logic
- Month-day correlation (April has 30 days, not 31) is not expressible in regex
For production date validation, always combine regex with a date parsing library.
Use Case
You are parsing log files with timestamps, extracting dates from unstructured text, or building a form that accepts dates in multiple formats and needs to identify which format the user entered.