Skip to content

Chat

Regex to validate semantic versions

Prism Code · 2 messages · 130 tokens

Give me a regex for semantic versions, with optional pre-release and build metadata.

Prism Code

This is the official pattern from the semver.org spec , which rejects leading zeros:

js
const SEMVER =
  /^(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-]+)*))?$/;

It captures major, minor, patch, pre-release and build in groups 1 to 5. Strings like 1.2 or 01.2.3 fail, which is what you want.

Sources

  • 1Semantic Versioning 2.0.0semver.org

Prism can make mistakes. Check important information.