Reputation: 498
I would like to write regex for matching an application version in javascript using pattern:
(0-255).(0-255)[.(0-65535).(0-65535)]
Here is my result:
^(?:(\d+)\.){1}(?:(\d+)\.){1}(?:(\d+)\.)?(\d+)?$
But it allows strings with dot in the end (like '111.222.333.') and doesn't limit number of digits. Any help?
Update
This pattern is better:
(0-255).(0-255)[.(0-65535)][.(0-65535)]
The result is:
^(?:[0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])[.](?:[0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?:(?:[.](?:[0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])){1})?(?:(?:[.](?:[0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])){1})?$
Upvotes: 1
Views: 143
Reputation: 48827
I think the best solution for you would be to split by .
and check each part:
function isInBounds(value, min, max) {
return !isNaN(value) && value >= min && value <= max;
}
function checkVersion(version) {
var parts = version.split(".");
switch (parts.length) {
case 4:
case 3:
for (var i = 2; i < parts.length; i++) {
if (!isInBounds(parseInt(parts[i], 10), 0, 65535)) {
return false;
}
}
// fallthrough
case 2:
for (var i = 0; i < 2; i++) {
if (!isInBounds(parseInt(parts[i], 10), 0, 255)) {
return false;
}
}
break;
default:
return false;
}
return true;
}
console.log(checkVersion("foo")); // false
console.log(checkVersion("foo.bar")); // false
console.log(checkVersion("foo.bar.foo")); // false
console.log(checkVersion("foo.bar.foo.bar")); // false
console.log(checkVersion("256")); // false
console.log(checkVersion("256.256")); // false
console.log(checkVersion("256.256.65536")); // false
console.log(checkVersion("256.256.65536.65536")); // false
console.log(checkVersion("42")); // false
console.log(checkVersion("42.42")); // true
console.log(checkVersion("42.42.42")); // true
console.log(checkVersion("42.42.42.42")); // true
See on jsFiddle
Regex is probably not the way to go, since it does not handle ranges very good. Just for the challenge, here is the one you would need (RegexForRange helped a lot ;)
):
^(?:[0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])[.](?:[0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?:(?:[.](?:[0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])){1,2})?$
Visualization by Debuggex
Upvotes: 1