The Pattern
``regex
^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\w.-]+))?(?:\+([\w.-]+))?$
`
Flags: gm ā multiline, so ^ and $ anchor to each line rather than the whole input.
What It Accepts and Rejects
| Input | Result |
|---|---|
1.0.0 | ā matches |
2.13.4-beta.1 | ā matches |
3.0.0+build.7 | ā matches |
1.0 | ā rejected |
01.2.3 | ā rejected |
Leading Zeros Are Illegal
Each numeric component is (0|[1-9]\d*) rather than \d+. That accepts 0 and rejects
01, which is exactly what the semver specification requires ā 01.2.3 is not a valid
version, and treating it as one breaks sorting.
The two optional groups are prerelease (-beta.1) and build metadata (+build.7). Semver
compares prerelease identifiers when ordering versions and ignores build metadata entirely,
so 1.0.0+a and 1.0.0+b are the same version.
The Limits of This Pattern
A valid semver string is not a valid *range*. Package manifests use range syntax ā
^1.2.3, ~1.2, >=1.0.0 <2.0.0 ā which this pattern rejects because it is a different
grammar. Use a semver library for range parsing and comparison; getting prerelease
precedence right by hand is more work than it looks.
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 .