The Pattern
``regex
^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$
`
Flags: gm — multiline, so ^ and $ anchor to each line rather than the whole input.
What It Accepts and Rejects
| Input | Result |
|---|---|
2026-08-30T13:45:00Z | ✅ matches |
2026-08-30T13:45:00.123+02:00 | ✅ matches |
2026-08-30 13:45:00 | ❌ rejected |
The T and the Offset Are Not Optional
ISO 8601's interchange profile (RFC 3339, which is what APIs actually use) requires the
literal T between date and time and a timezone designator at the end — either Z for
UTC or an explicit ±HH:MM offset.
That is why 2026-08-30 13:45:00 is rejected: a space instead of T, and no offset. It
is an extremely common malformed timestamp, and accepting it silently is how "the timestamps
are eight hours off" bugs begin.
Fractional seconds are optional and unbounded in precision: \.\d+ accepts milliseconds,
microseconds and nanoseconds alike.
The Limits of This Pattern
The pattern checks shape, not validity: 2026-02-31T00:00:00Z matches and is not a real
date. It also rejects several legal ISO 8601 forms — week dates (2026-W35-1), ordinal
dates (2026-242) and basic format without separators (20260830T134500Z) — which are
valid in the full standard but rare in APIs. Parse with a date library before trusting the
value.
Testing Before Shipping
A regex that has only been tried against inputs you expect to match is untested. Every
pattern needs three kinds of case:
1. Valid inputs that should match, including the awkward-but-legal ones.
2. Invalid inputs that should not, especially near-misses that differ by one character.
3. Adversarial inputs — very long strings, unusual Unicode, and nesting that could
trigger catastrophic backtracking.
Paste your own examples into the tester above and watch which lines highlight. A pattern
that matches everything you throw at it is usually too permissive rather than correct.
Catastrophic Backtracking
Nested quantifiers over overlapping character classes — (a+)+, (\w+\s?)* — can take
exponential time on a non-matching input. On a server that is a denial-of-service bug, not a
performance issue. If a pattern is applied to user input, bound the input length first and
prefer explicit alternation over nested repetition.
Anchors, Greediness and Backtracking
Three behaviours account for most regex surprises, and this pattern shows all three.
Anchors. ^ and $ pin the match to the start and end of the input. Without them,
\d{3} matches the 123 inside abc123def. With m in the flags — as here — they
pin to each *line* instead, which is what lets one pattern be tested against a list.
Greediness. .* takes as much as it can and gives back only when forced; .*? takes
as little as possible. On , the pattern <.*> matches the whole string and
<.*?> matches just .