javascript extracting floating point numbers regex are not matched properly

50 Views Asked by At

I've below javascript program -

var rx = /^the values should(?: between (\d+(\.\d+)?) and (\d+(\.\d+)?))$/;
var sentence = "the values should between 1.1 and 2.7";
var arr = rx.exec(sentence);
console.log(JSON.stringify(arr));

I want to extract the number 1.1 and 2.7 into into an array from the matched line.

When I run the above program I get the below result

["the values should between 1.1 and 2.7","1.1",".1","2.7",".7"]

In the above program 1.1 becomes .1 and 2.7 becomes .7.

How can I match it in javascript correctly.

2

There are 2 best solutions below

2
Éric On BEST ANSWER

Pointy is right in suggesting in his/her comment a better use of non capturing parentheses: (?: ... ), to avoid unwanted captures.

I also understand that the first element of your output array is unwanted, so you can use the Array.prototype.shift() function to remove it.

Your code could be:

var rx = /^the values should between (\d+(?:\.\d+)?) and (\d+(?:\.\d+)?)$/;
var sentence = "the values should between 1.1 and 2.7";
var arr = rx.exec(sentence);
arr.shift(); // Remove the first element of the array.
console.log(JSON.stringify(arr));

Edit:
CAustin judiciously questionned about the outer non-capturing parentheses in the original regex, which I left in my initial answer. On reflection, they seemed useless to me, so I removed them to simplify the regex.

0
Alexander Nenashev On

You can use a character group [\d.] if the float values are expected formatted properly:

var rx = /^the values should between ([\d.]+) and ([\d.]+)$/;
var sentence = "the values should between 1.1 and 2.7";
var [, from, to] = rx.exec(sentence);
console.log(from, to);