C.W.K.
Stream
Lesson 08 of 12 · published

Version Numbers (Semver)

~6 min · semver, version, validation

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

The semver shape

Semantic Versioning is the MAJOR.MINOR.PATCH format that anchors most software releases. The basic regex:

^\d+\.\d+\.\d+$

Three numeric parts joined by dots. 1.0.0 matches; 1.0 doesn't.

The full semver pattern

Real semver allows pre-release suffixes (1.0.0-alpha, 1.0.0-rc.1) and build metadata (1.0.0+build.123). The official regex from the semver spec:

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

Yes, that's the official one. Yes, you should look it up rather than memorize it. The README of the semver spec on GitHub has it.

For ad-hoc usage

Most of the time you don't need full semver — you need "matches a version-shape thing." The simple \d+\.\d+\.\d+ covers most cases.

Comparing versions

Don't compare versions with regex — extract the parts, then compare numerically. Python: packaging.version.parse. Node: semver npm package. Go: standard library handling.

Code

Semver patterns·python
import re

# Simple
SEMVER = re.compile(r'^\d+\.\d+\.\d+$')
bool(SEMVER.fullmatch('1.0.0'))      # True
bool(SEMVER.fullmatch('1.0.0-rc'))   # False
bool(SEMVER.fullmatch('1.0'))        # False

# Extract version from string with optional v-prefix
VERSION = re.compile(r'\bv?(\d+\.\d+\.\d+)(?:-([\w.]+))?(?:\+([\w.]+))?\b')
m = VERSION.search('release v2.3.1-beta.2 deployed')
print(m.group(1))  # '2.3.1'
print(m.group(2))  # 'beta.2'

# For comparison, use a library
from packaging.version import Version

v1 = Version('1.10.0')
v2 = Version('1.9.0')
v1 > v2  # True (numeric, not string)

External links

Exercise

Take a CHANGELOG file. Extract every version number with a regex. Sort them with the library. The sorted output should put 2.10.0 AFTER 2.9.0 — which string sort would fail at.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.