How to Match Multiple Date Formats with Regex?
Matching dates can be tricky due to various formats. This regex pattern helps you capture MM/DD/YYYY, YYYY-MM-DD, and DD Month YYYY formats seamlessly.
Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.
The formula
"Match dates in MM/DD/YYYY, YYYY-MM-DD, and DD Month YYYY formats"
^(\d{1,2}/\d{1,2}/\d{4}|\d{4}-\d{1,2}-\d{1,2}|\d{1,2} \w+ \d{4})$
This regex pattern matches dates in three specified formats: MM/DD/YYYY, YYYY-MM-DD, and DD Month YYYY.
Step-by-step breakdown
- The pattern starts with ^ to indicate the beginning of the string.
- It uses ( ) to group the three date formats together.
- Each format is separated by | which acts as an OR operator.
- The \d{1,2} matches one or two digits for day or month.
- The \d{4} matches exactly four digits for the year.
- The \w+ matches one or more word characters for the month name.
Edge cases & warnings
- Input with invalid dates like 13/01/2020 or 2020-02-30.
- Input with mixed formats in the same string.
- Input with leading zeros like 01/01/2020 or 2020-01-01.
- Input with extra spaces or punctuation.
- Input with abbreviated month names like 01 Jan 2020.
Examples
"12/31/2020"
Match
"2020-12-31"
Match
Frequently asked questions
Can this regex match leap year dates?
Yes, but it does not validate the actual date; it only matches the format.
What if I want to include time with the date?
You would need to modify the regex to accommodate the time format.
How can I test this regex pattern?
You can use online regex testers or programming environments that support regex.
Can't find what you need?
Describe a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.