我正在尝试匹配以下示例中的第一组数字。
some stuff (6 out of 10 as a rating)
需要返回6
some stuff (2.3 out of 10 as a rating)
需要返回2.3
some stuff (10 out of 10 as a rating)
需要返回10
此外,有时字符串不会有数字
some stuff but nothing else
答案 0 :(得分:2)
var match = /\d+(\.\d+)?/.exec("some stuff (10 out of 10 as a rating)");
alert(match[0]);
\d
匹配任何数字,0-9 +
表示1个或更多\.
匹配a。?
表示0或1 总的来说,这意味着任意数字(0-9)可选地后跟一个小数点后跟一个或多个数字。
作为一项功能:
var getFirstNumber = function(input){
var match = /\d+(\.\d+)?/.exec(input);
return match[0];
};
答案 1 :(得分:0)
您可以尝试此'some stuff (2.3 out of 10 as a rating)'.match(/\D*(\d\.?(\d)*)/)[1]