输入:“277.79° "(包含一个数字和一个表示温度的字符的字符串)
所需输出:“277.79”
再举一个例子来说明这一点:输入"-8.7°F"
需要返回输出:"-8.7"
**我尝试过的方法:**我尝试过使用regex
let pattern = /^[0-9]*\.?[0-9]*$/
let num = pattern.test("277.79°K")
这将返回true或false,以确认我有我正在寻找的正数类型(还没有得到处理负数的东西)
然而,当我尝试.match进行实际提取时,它说它的值为null。thenum = "277.79°K".match(/^[0-9]*\.?[0-9]*\n/) //returns null
- 编辑:* 我越来越接近,并有这个代码,可以提取数字,如果它后面有一个空格,但不是如果程度或字母立即跟随数字没有空格。
let rx1 = /( |^)([+-]?[0-9]*\.?[0-9]*)( |$)/g
temp = rx1.exec('-277.79 °K') //returns ['-277.79 '...]
temp = rx1.exec('-277.79°K') //returns null
**因此主要问题:**我可以测试true/false,但是我不能成功地编写一个函数,从字符串中 * 提取 * 我需要的部分。
2条答案
按热度按时间nbysray51#
你想要这种效果吗?
nhn9ugyo2#
所以你想提取数字,而不仅仅是匹配,这里有一个函数提取它找到的第一个数字,或者
NaN
(不是数字),如果没有:输出:
正则表达式的解释:
-?
-可选的-
[0-9]+
--1位以上数字(\.[0-9]*)?
-.
的可选模式,后跟数字