Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript regex to test a number (integer or decimal, positive or negative ) range

I want to find out whether a string is a valid range with - as a separator. Examples like these should pass the test:

1-5
1-10.1
10.5-20.5
-10.5-8
-2--1 << minus two to minus one
-3.5--1
-20.5--2.1

The negative to negative range may seem weird without spaces but I’m stuck with that.

Do you think this regex is good enough for the job?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/(-?[0-9]+[.]*)+-(-?[0-9]+[.]*)+/

>Solution :

Regex does not perform arithmetic so making sure the left-side number is less than the right side requires additional processing.

You can verify the input is in the correct format and extract the numbers by making use of capture groups:

^(-?\d*\.?\d+)-(-?\d*\.?\d+)$
  • ^ – start of line
  • ( – start capture group
    • -? – optional dash (negative)
    • \d*\.?\d+ – allow floating or whole number
  • ) – end capture group
  • - – range dash
  • ( – start capture group
    • -? – optional dash (negative)
    • \d*\.?\d+ – allow floating or whole number
  • ) – end capture group
  • $ – end of line

https://regex101.com/r/m6cT2o/1

However, to verify that the first number is smaller than the second number requires additional JS processing.

var rangeRegex = /^(-?\d*\.?\d+)-(-?\d*\.?\d+)$/;
var str = '-10.5-8';

var array = str.match(rangeRegex);

if( array !== null && array[1] < array[2]){
  console.log('good');
}
else{
  console.log('bad');
}

console.log(array);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading