Regex patterns/Validation

Semantic version

major.minor.patch, with optional prerelease and build metadata.

/^\d+\.\d+\.\d+(?:-[\w.]+)?(?:\+[\w.]+)?$/
Open it in Rex

The problem

Check that a string is a semantic version number, optionally with prerelease or build metadata.

How it reads

start\drepeat\.\drepeat\.\drepeatgroup-[\w.]repeatskipgroup\+[\w.]repeatskipend

Follow the line from left to right — every path you can trace is a string this pattern matches.

  1. ^\d+\.\d+\.\d+(?:-[\w…In order:
  2. ^The start of the text (or of a line with the m flag)
  3. \d+A digit, one or more times, as many as possible
  4. \.The character "."
  5. \d+A digit, one or more times, as many as possible
  6. \.The character "."
  7. \d+A digit, one or more times, as many as possible
  8. (?:-[\w.]+)?Repeated optionally (zero or one time):
  9. (?:-[\w.]+)Group (not captured):
  10. -[\w.]+In order:
  11. -The character "-"
  12. [\w.]+Any one of: a word character (letter, digit or underscore) or ".", one or more times, as many as possible
  13. (?:\+[\w.]+)?Repeated optionally (zero or one time):
  14. (?:\+[\w.]+)Group (not captured):
  15. \+[\w.]+In order:
  16. \+The character "+"
  17. [\w.]+Any one of: a word character (letter, digit or underscore) or ".", one or more times, as many as possible
  18. $The end of the text (or of a line with the m flag)

Matches

  • 1.0.0
  • 2.13.4-beta.1
  • 3.0.0+build.27
  • 0.0.1-rc.1+exp.sha.5114f85

Does not match

  • v1.0
  • 1.0
  • 1.0.0.0
  • latest

Where it bites

  • A leading v (v1.0.0) is rejected — npm tags often carry one, so strip it first or add v? to the front.
  • The + must be escaped. Unescaped it is a quantifier, and the pattern silently means something else.
  • The official semver regex also forbids leading zeros in the numbers; this one allows 01.0.0.

More validation patterns