views:

34

answers:

2

Input:

"NEW YORK (Reuters) U.S. stock index futures pointed to a slight rebound on Wall Street on Wednesday, with futures for the S&P 500 up 0.34 percent, Dow Jones futures up 0.12 percent and Nasdaq 100 futures up 0.51 percent at 0921 GMT."

Output should be array of all numbers including floats.

A little similar thread but it extracts only one number.

+3  A: 

this should do it:

var text = "NEW YORK (Reuters) U.S. stock index futures pointed to a slight rebound on Wall Street on Wednesday, with futures for the S&P 500 up 0.34 percent, Dow Jones futures up 0.12 percent and Nasdaq 100 futures up 0.51 percent at 0921 GMT.";
console.log(text.match(/(\d[\d\.]*)/g));

you can filter out the invalid numbers e.g. 55.55.55 with the following code:

var numbers = [];
text.replace(/(\d[\d\.]*)/g, function( x ) { var n = Number(x); if (x == n) { numbers.push(x); }  })
KARASZI István
+1  A: 

This regular expression should work:

/[-+]?[0-9]*\.?[0-9]+/g

A test:

"NEW YORK (Reuters) U.S. stock index futures pointed to a slight rebound on Wall Street on Wednesday, with futures for the S&P 500 up 0.34 percent, Dow Jones futures up 0.12 percent and Nasdaq 100 futures up 0.51 percent at 0921 GMT.".match(/[-+]?[0-9]*\.?[0-9]+/g)

returns this Array:

["500", "0.34", "0.12", "100", "0.51", "0921"]
Matt
your solution will fail on: "123.45.67 .56" for e.g.
KARASZI István
Depending on what you mean by "fail". It'd return `["123.45", ".67", ".56"]`. "123.45.67" is not a float. You might also say it'd fail on 1 000 000 or 1,000,000 - it just depends on what you need.
Matt