The Pattern
``regex
^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$
`
Flags: gm ā multiline, so ^ and $ anchor to each line rather than the whole input.
What It Accepts and Rejects
| Input | Result |
|---|---|
9f1c8a2e-7b3d-4f6a-9c2e-1d8b4a6f3c07 | ā matches |
00000000-0000-0000-0000-000000000000 | ā rejected |
not-a-uuid | ā rejected |
Version and Variant Are Encoded in the String
The third group starts with [1-5], which is the UUID version, and the fourth starts with
[89abAB], which is the RFC 4122 variant field. That is why the nil UUID
00000000-0000-0000-0000-000000000000 is rejected here: it has version 0 and variant 0, and
is a valid special value rather than a generated identifier.
A looser pattern using [0-9a-fA-F] in every position accepts the nil UUID and any
random hex in the right shape.
The Limits of This Pattern
The pattern predates UUIDv7, which is version 7 and therefore rejected by [1-5]. If you
are using time-ordered UUIDv7 identifiers ā increasingly common for database keys ā widen
the class to [1-8]. Validating shape also says nothing about whether the identifier
exists; only a lookup can tell you that.
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 .