admin管理员组文章数量:1356455
I need a RegEx (for Javascript) for the numeric range of 2-255 and I'm having difficulty modifying similar RegExes to this purpose.
^([2-9]|1[0-6])$
That is 2-16 but I can't quite get the third digit correctly.
I need a RegEx (for Javascript) for the numeric range of 2-255 and I'm having difficulty modifying similar RegExes to this purpose.
^([2-9]|1[0-6])$
That is 2-16 but I can't quite get the third digit correctly.
Share Improve this question asked Feb 9, 2017 at 18:52 SpaceNinjaSpaceNinja 5127 silver badges22 bronze badges 2- 4 Are you sure that you need regex for this ? – Belmin Bedak Commented Feb 9, 2017 at 18:56
- @BelminBedak It's one of many patterns I'm testing for in an Angular application, so I would like to keep this pattern along with all the others to stay consistent. – SpaceNinja Commented Feb 9, 2017 at 19:23
5 Answers
Reset to default 7^([2-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$
This matches 2-9, 10-99, 100-199, 200-249, and 250-255.
The solution using RegExp.prototype.test()
function:
var pattern = /^([2-9]|\d{2}|1\d{2}|2[0-4]\d|2[0-5][0-5])$/;
console.log(pattern.test(3));
console.log(pattern.test(300));
console.log(pattern.test(123));
console.log(pattern.test(255));
console.log(pattern.test(10));
console.log(pattern.test(256));
console.log(pattern.test(1));
console.log(pattern.test(199));
console.log(pattern.test(249));
However, there's some better approach for such case:
var inRange = function (num) {
var num = Number(num);
return !isNaN(num) && (num % 1 === 0) && num >= 2 && num < 256;
};
console.log(inRange(254.4));
console.log(inRange(255));
One of the shortest solutions using RegExp may be
^([2-9]\d?|1\d\d?|2([0-4]\d|5[0-5]))$
[2-9]\d?
- to match 2-9, 20-991\d\d?
- to match 10-19, 100-1992([0-4]\d|5[0-5])
- to match 200-255
^([2-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$
Figured it out! It's:
\b(?:2[0-4][0-9]{2}|25[0-5]|[1-9][0-9]|1[0-9]{2}|[2-9])\b
本文标签: javascriptRegular Expression for Integer Range of 2255Stack Overflow
版权声明:本文标题:javascript - Regular Expression for Integer Range of 2-255 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743985380a2571254.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论