skip to Main Content

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

Answers


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

    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search