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?
/(-?[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);