javascriptregexregex-group

javascript extracting floating point numbers regex are not matched properly


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.


Solution

  • 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.