0

I want to use Regex to match numbers between 0 to 25 both inclusive which can be doubles with 1 precision.

For ex.- 2, 2.5, 23.0, 8, 24.3, 25

I created following regex-

^(\\s*|0?[0-9]|[0-9]|1[0-9]|2[0-5])$

But it works only for numbers between 0 to 25 both inclusive.

sjain
  • 23,126
  • 28
  • 107
  • 185

2 Answers2

0

To verify the validity, use the >= and <= operators. To meet the regex requirement, just add a garbage regex expression.

let isMatch = number => {
  'must use regex'.match(/x/);
  return number >= 0 && number <= 25;
};
junvar
  • 11,151
  • 2
  • 30
  • 46
0

This is the regex pattern I would use here:

^(?:(?:[0-9]|1[0-9]|2[0-4])(?:\.[0-9])?|25(?:\.0)?)$

Demo

The pattern is similar to what you used, except that we only match 2[0-4] with any single decimal point. The end point 25 is a special case, which can only take 25.0 at most for its decimal component.

But in general it would easier in JavaScript to just parse the text number, and then use an inequality to check the range. E.g.

var number = '24.3'
if (number >= 0 && number <= 25.0) {
    console.log('within range');
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360