Regex for Semantic Versions (SemVer)
SemVer versions are MAJOR.MINOR.PATCH, with an optional pre-release (-rc.1) and build metadata (+build.5). This is the pattern published on semver.org: it rejects leading zeros in numeric parts (01.2.3) and captures each component in its own group.
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/How it works, token by token
| Token | Meaning |
|---|---|
| ^(0|[1-9]\d*) | major version: 0, or a number without leading zeros (group 1) |
| \.(0|[1-9]\d*) | a dot, then the minor version (group 2) |
| \.(0|[1-9]\d*) | a dot, then the patch version (group 3) |
| (?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))? | optional pre-release after a hyphen: dot-separated identifiers, numeric ones without leading zeros (group 4) |
| (?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))? | optional build metadata after a plus sign (group 5) |
| $ | end of string |
What it matches
1.2.30.1.02.0.0-rc.11.0.0-alpha+00110.20.301.201.2.3v1.2.31.2.3-Try it live
One candidate per line — the m flag makes the ^ and $ anchors apply to each line. Edit anything; it runs in your browser.
Variations
^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$release versions only, with an optional v prefix as in Git tags^(\d+)\.(\d+)(?:\.(\d+))?$loose: 1.2 or 1.2.3, leading zeros allowedLanguage notes
- semver.org also publishes a named-group version. JavaScript and .NET write named groups as (?<major>…); Python and Go use (?P<major>…).
Frequently asked questions
Why reject 01.2.3?
The SemVer spec forbids leading zeros in numeric identifiers, so 01.2.3 isn't a valid version. The pattern enforces it with 0|[1-9]\d*.
How do I compare two versions?
Not with a regex or a string comparison — as text, '1.10.0' sorts before '1.9.0'. Convert the groups to integers, or use a library such as semver on npm.
Building something custom? The regex tester gives you live match highlighting for any pattern.