gpt4 book ai didi

Javascript正则表达式匹配被其他字符污染的小数

转载 作者:行者123 更新时间:2023-12-02 20:04:22 25 4
gpt4 key购买 nike

我正在尝试匹配以下示例中的第一组数字。

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

最佳答案

var match = /\d+(\.\d+)?/.exec("some stuff (10 out of 10 as a rating)");
alert(match[0]);
  • \d 匹配任何数字,0-9
  • + 表示 1 个或多个
  • \. 匹配 .
  • ? 表示 0 或 1

所以总的来说,它意味着任意数量的数字(0-9),可选地后跟一个小数点,后跟 1 个或更多数字。

作为函数:

var getFirstNumber = function(input){
var match = /\d+(\.\d+)?/.exec(input);
return match[0];
};

关于Javascript正则表达式匹配被其他字符污染的小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7627145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com