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
| Input | Result |
|---|---|
| ^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
JavaScript Variable Name
Valid JavaScript variable/identifier name
Python Variable Name
Valid Python identifier name
CSS Class Name
Valid CSS class name (starts with letter, underscore, or hyphen)
CSS ID Selector
CSS ID selector starting with #
JSON Key
JSON object key (quoted string followed by colon)
Semantic Version (Strict)
Strict semantic versioning (MAJOR.MINOR.PATCH)