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
Add a ment  | 

5 Answers 5

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-99
  • 1\d\d? - to match 10-19, 100-199
  • 2([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