Regex for Semantic Versioning (SemVer) — Pattern from semver.org

Official SemVer 2.0.0 regex for matching MAJOR.MINOR.PATCH versions with optional pre-release and build metadata. Tested examples for npm, Cargo, and Go modules.

Data Validation

Detailed Explanation

Regex for Semantic Versioning

The SemVer 2.0.0 specification publishes an official regex for validating version strings. It enforces three numeric parts plus optional pre-release identifiers and build metadata.

Official SemVer Regex

^(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-]+)*))?$

What Each Section Validates

Group Purpose Rule
MAJOR First number No leading zeros (0 allowed, 01 not)
MINOR Second number Same rule
PATCH Third number Same rule
Pre-release After - Dot-separated identifiers, alphanumeric or numeric without leading zeros
Build After + Dot-separated alphanumeric identifiers

Tested Examples

Input Valid?
1.0.0 yes
2.10.3 yes
1.0.0-alpha yes
1.0.0-alpha.1 yes
1.0.0-0.3.7 yes
1.0.0+build.1 yes
1.0.0-beta+exp.sha.5114f85 yes
01.0.0 no (leading zero)
1.0 no (missing PATCH)
1.0.0- no (empty pre-release)

Named Capture for Component Extraction

^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<prerelease>[0-9A-Za-z.-]+))?(?:\+(?<build>[0-9A-Za-z.-]+))?$

Practical Notes

Tools like npm, Cargo, Composer, and Go modules all consume SemVer. For comparison logic (greater-than, range matching), use a dedicated library such as semver on npm rather than regex.

Use Case

Validating version tags in a release pipeline, parsing dependency versions in lockfiles, or rejecting malformed input in a CI publishing step before pushing to a package registry.

Try It — Regex Cheat Sheet

Open full tool