Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of string before '2023' in '2023-10-05 14:30:00' |
\d |
Digit character class (0-9) | Any digit like '2' in '2023' |
{4} |
Quantifier: exactly 4 occurrences of the preceding token | Four digits '2023' |
- |
Literal hyphen character | Hyphen between '2023' and '10' |
\d |
Digit character class (0-9) | Any digit like '1' in '10' |
{2} |
Quantifier: exactly 2 occurrences of the preceding token | Two digits '10' |
- |
Literal hyphen character | Hyphen between '10' and '05' |
\d |
Digit character class (0-9) | Any digit like '0' in '05' |
{2} |
Quantifier: exactly 2 occurrences of the preceding token | Two digits '05' |
|
Literal space character | Space between date and time |
\d |
Digit character class (0-9) | Any digit like '1' in '14' |
{2} |
Quantifier: exactly 2 occurrences of the preceding token | Two digits '14' |
: |
Literal colon character | Colon between '14' and '30' |
\d |
Digit character class (0-9) | Any digit like '3' in '30' |
{2} |
Quantifier: exactly 2 occurrences of the preceding token | Two digits '30' |
: |
Literal colon character | Colon between '30' and '00' |
\d |
Digit character class (0-9) | Any digit like '0' in '00' |
{2} |
Quantifier: exactly 2 occurrences of the preceding token | Two digits '00' |
(?: |
Non-capturing group start (does not capture matched text) | Start of optional milliseconds group |
, |
Literal comma character | Comma before milliseconds |
\d |
Digit character class (0-9) | Any digit like '1' in '123' |
{3} |
Quantifier: exactly 3 occurrences of the preceding token | Three digits '123' |
) |
Non-capturing group end | End of optional milliseconds group |
? |
Quantifier: 0 or 1 occurrence of the preceding non-capturing group | Optional presence of ',123' |
$ |
Anchor: asserts position at end of the string | End of string after '00' or ',123' |
Matches
2023-10-05 14:30:002023-12-31 23:59:592000-01-01 00:00:00,1231999-09-09 09:09:09,999
Does not match
2023-10-5 14:30:002023-10-05 14:30:02023-10-05 14:30:00,122023-10-05 14:30:00,12342023/10/05 14:30:002023-10-05T14:30:002023-10-05 14:30:00
Common pitfalls
- Forgetting to escape the hyphens and colons in some regex flavors (not needed in JavaScript for these literals)
- Assuming the milliseconds part is mandatory (it is optional due to the ? quantifier)
- Not anchoring the pattern with ^ and $, which could lead to partial matches in longer strings
- Confusing \d with \D (non-digit) or misusing character classes
Performance notes
The pattern is linear in complexity with no nested quantifiers or alternations, so catastrophic backtracking is not a concern. Anchoring with ^ and $ ensures the entire string is validated, improving efficiency. The non-capturing group (?:...) is used for grouping without capturing, which is slightly more efficient than a capturing group.