DD
DevDash

Regex for SemVer Range (npm-style)

Regex Pattern

^[~^]?(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?)?$

npm-style version range with optional ~ or ^ prefix

Quick Answer

The regex pattern for semver range (npm-style) is `^[~^]?(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?)?$`. npm-style version range with optional ~ or ^ prefix. This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.

Test Examples

InputResult
^1.0.0✓ Matches
~2.3.4✓ Matches
1.0.0✓ Matches
^0.1✓ Matches
v1.0.0✗ No match
>=1.0.0✗ No match
*✗ No match
latest✗ No match

Code Examples

javascript

const regex = /^[~^]?(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?)?$/;
const isValid = regex.test(value);

python

import re
pattern = r'^[~^]?(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?)?$'
if re.match(pattern, value):
    print("valid")

ruby

pattern = /^[~^]?(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?)?$/
if value =~ pattern
  puts "valid"
end

php

if (preg_match('/^[~^]?(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?)?$/', $value)) {
    echo "valid";
}

java

String pattern = "^[~^]?(0|[1-9]\\d*)(?:\\.(0|[1-9]\\d*)(?:\\.(0|[1-9]\\d*))?)?$";
boolean isValid = value.matches(pattern);

Frequently Asked Questions

Related Regex Patterns

Want API access + no ads? Pro coming soon.