Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Starts matching from the beginning |
(0|[1-9]\d*) |
Group 1: Matches either '0' or a non-zero digit followed by any number of digits (major version number) | 0, 1, 123 |
\. |
Literal dot: separates version components | . |
(0|[1-9]\d*) |
Group 2: Matches either '0' or a non-zero digit followed by any number of digits (minor version number) | 0, 1, 45 |
\. |
Literal dot: separates version components | . |
(0|[1-9]\d*) |
Group 3: Matches either '0' or a non-zero digit followed by any number of digits (patch version number) | 0, 1, 99 |
(?: |
Non-capturing group start: groups optional pre-release and build metadata | Starts optional group |
- |
Literal hyphen: introduces pre-release version | - |
((?:0|[1-9]\d*|[a-zA-Z-][a-zA-Z0-9-]*)) |
Group 4: Matches pre-release identifier (digits or alphanumeric with hyphens, starting with a letter or hyphen) | alpha, 1, beta-1 |
(?: |
Non-capturing group start: groups optional build metadata | Starts optional build metadata group |
\\( |
Escaped literal parenthesis: introduces build metadata | \( |
(?:0|[1-9]\d*|[a-zA-Z-][a-zA-Z0-9-]*) |
Non-capturing group: matches build metadata (digits or alphanumeric with hyphens, starting with a letter or hyphen) | 2023, x86-64 |
) |
Literal parenthesis: closes build metadata group | ) |
)? |
Quantifier: makes the entire build metadata group optional | Optional build metadata |
)? |
Quantifier: makes the entire pre-release and build metadata group optional | Optional pre-release and build |
$ |
Anchor: asserts position at end of the string | Ends matching at the end |
Matches
1.2.30.0.010.20.301.2.3-alpha1.2.3-beta-11.2.3+20231.2.3-alpha+20231.2.3-1+build-2023
Does not match
.1.2.31..2.31.2.1.2.3-1.2.3-+build1.2.3-alpha(build)1.2.3-011.2.3-@invalid
Common pitfalls
- Forgetting that pre-release identifiers cannot start with a digit unless the entire identifier is numeric (e.g., '1' is valid but '01' is not).
- Assuming the build metadata can contain spaces or special characters beyond hyphens and alphanumerics.
- Not accounting for the strict ordering of version components (major.minor.patch-pre-release+build).
- Overlooking that the entire pre-release and build metadata section is optional.
Performance notes
The regex is generally efficient due to the use of non-capturing groups and quantifiers. However, nested quantifiers (e.g., \d*) in alternations could lead to catastrophic backtracking in pathological cases. Anchoring (^ and $) ensures the entire string is validated, preventing partial matches.