Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts the position at the start of the string | Start of '2023-12-31' |
\d |
Character class: matches any digit (0-9) | Digit '2' in '2023-12-31' |
{4} |
Quantifier: specifies exactly 4 occurrences of the preceding token | Four digits '2023' in '2023-12-31' |
- |
Literal hyphen character | Hyphen '-' in '2023-12-31' |
\d |
Character class: matches any digit (0-9) | Digit '1' in '12' |
{2} |
Quantifier: specifies exactly 2 occurrences of the preceding token | Two digits '12' in '2023-12-31' |
- |
Literal hyphen character | Hyphen '-' in '2023-12-31' |
\d |
Character class: matches any digit (0-9) | Digit '3' in '31' |
{2} |
Quantifier: specifies exactly 2 occurrences of the preceding token | Two digits '31' in '2023-12-31' |
$ |
Anchor: asserts the position at the end of the string | End of '2023-12-31' |
Matches
2023-12-310000-00-009999-99-991234-56-78
Does not match
2023/12/312023-12-32023-12-3112023-13-012023-12-3a2023-12-312023-12-312023-12-31-extra
Common pitfalls
- Does not validate date logic (e.g., '2023-02-30' is matched but invalid)
- Does not account for leading/trailing whitespace (use \s* or trim input first)
- Does not handle alternative date separators (e.g., '/')
- Does not enforce month/day ranges (e.g., month 13 or day 32)
- Fails on strings with extra characters before/after the date
Performance notes
No catastrophic backtracking risk due to fixed quantifiers and simple structure. Anchors (^ and $) ensure the regex matches the entire string, improving efficiency. For large inputs, consider anchoring to avoid partial matches.