2010-10-20 37 views
4

输入:的Javascript:如何从字符串中提取多个号码

“(纽约讯)美国股市指数期货华尔街小幅反弹,周三,随着期货对于S &普500上涨0.34%,道琼斯指数上涨0.12%,纳斯达克100指数上涨0.51%,格林威治时间0921。“

输出应该是所有数字的数组,包括浮点数。

有点类似thread但它只提取一个数字。

+1

正则表达式是要走的路数 – Onkelborg 2010-10-20 11:30:42

回答

7

这应该这样做:

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)); 

可以例如过滤掉无效的电话号码55.55.55用下面的代码:

var numbers = []; 
text.replace(/(\d[\d\.]*)/g, function(x) { var n = Number(x); if (x == n) { numbers.push(x); } }) 
3

这个正则表达式应该工作:

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

测试:

"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) 

返回此Array:

["500", "0.34", "0.12", "100", "0.51", "0921"] 
+0

您的解决方案将失败:例如“123.45.67 .56” – 2010-10-20 11:49:13

+3

取决于你的意思是“失败”。它会返回'[“123.45”,“.67”,“.56”]'。 “123.45.67”不是浮动。你可能会说它会失败100万或1,000,000 - 这取决于你需要什么。 – Matt 2010-10-20 12:44:07

+0

这是我用过的。谢谢 – 2017-09-27 16:16:23

相关问题