Regex for semantic version (semver)

Use /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/ to check that a whole string is a valid for semantic version (semver). Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/
Open in Regex Tester
InputResultGroups
1.0.0✓ Match1 0 0
2.10.3-beta.1✓ Match2 10 3 beta.1
1.0.0+build.5✓ Match1 0 0 build.5
0.1.0-rc.1+sha.5114f85✓ Match0 1 0 rc.1 sha.5114f85
1.0✗ No match
01.0.0✗ No match
v1.0.0✗ No match
1.0.0-✗ No match

How the pattern works

PartMeaning
(0|[1-9]\d*)Major, minor and patch (groups 1–3): numbers without leading zeros
\.Dots between them
(?:-([0-9A-Za-z.-]+))?Optional pre-release after a hyphen (group 4): beta.1, rc.2
(?:\+([0-9A-Za-z.-]+))?Optional build metadata after a plus (group 5)

Code examples

JavaScript

const re = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/;
re.test(value); // true or false

Python

import re

bool(re.fullmatch(r'(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?', value))

PHP

preg_match('/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/', $value) === 1;

Notes and limitations

A practical version of the semver 2.0 rules; strip a leading v first if your tags use one. Compare versions numerically, group by group, not as strings.

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex for semantic version (semver)?
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: 1.0.0, 2.10.3-beta.1, 1.0.0+build.5, 0.1.0-rc.1+sha.5114f85. The others don’t.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.