Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts the position at the start of the string | Start of '2023-05-15' |
\d |
Character class: matches any digit (0-9) | Digit '2' in '2023' |
{4} |
Quantifier: exactly 4 occurrences of the preceding token | Four digits '2023' |
- |
Literal hyphen character | Hyphen '-' in '2023-' |
(?: |
Non-capturing group start (grouping without capturing) | Group '0[1-9]|1[0-2]' for month |
0 |
Literal character '0' | '0' in '05' |
[1-9] |
Character class: matches any digit from 1 to 9 | '5' in '05' |
| |
Alternation: OR operator between patterns | Separates '0[1-9]' and '1[0-2]' |
1 |
Literal character '1' | '1' in '10' |
[0-2] |
Character class: matches digits 0, 1, or 2 | '0' in '10' |
) |
Non-capturing group end | End of month group |
- |
Literal hyphen character | Hyphen '-' in '-05-' |
(?: |
Non-capturing group start (grouping without capturing) | Group '0[1-9]|[12][0-9]|3[01]' for day |
0 |
Literal character '0' | '0' in '05' |
[1-9] |
Character class: matches any digit from 1 to 9 | '5' in '05' |
| |
Alternation: OR operator between patterns | Separates '0[1-9]', '[12][0-9]', and '3[01]' |
[12] |
Character class: matches digits 1 or 2 | '1' or '2' in '15' or '29' |
[0-9] |
Character class: matches any digit (0-9) | '5' in '15' or '9' in '29' |
| |
Alternation: OR operator between patterns | Separates '[12][0-9]' and '3[01]' |
3 |
Literal character '3' | '3' in '31' |
[01] |
Character class: matches digits 0 or 1 | '0' or '1' in '30' or '31' |
) |
Non-capturing group end | End of day group |
$ |
Anchor: asserts the position at the end of the string | End of '2023-05-15' |
Matches
2023-05-151999-12-310001-01-01
Does not match
2023-13-012023-00-152023-05-322023/05/152023-5-152023-05-12023-5-1
Common pitfalls
- Does not validate leap years (e.g., '2023-02-29' is accepted but invalid)
- Does not account for varying month lengths (e.g., April has 30 days)
- Does not handle single-digit months/days without leading zeros (e.g., '2023-5-5')
- Fails to reject invalid dates like '2023-02-30'
Performance notes
The regex is efficient with no catastrophic backtracking risk due to the non-capturing groups and clear alternation boundaries. Anchors (^ and $) ensure full-string matching, preventing partial matches.