使用regex从字符串的开头只提取一个十进制数

5fjcxozz  于 2022-12-30  发布在  其他
关注(0)|答案(2)|浏览(124)

输入:“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,但是我不能成功地编写一个函数,从字符串中 * 提取 * 我需要的部分。

nbysray5

nbysray51#

const paragraph = '277.79°K';
const regex = /^-?\d{1,4}\.?(\d{1,3})?/;
const found = paragraph.match(regex);

console.log(found);

你想要这种效果吗?

nhn9ugyo

nhn9ugyo2#

所以你想提取数字,而不仅仅是匹配,这里有一个函数提取它找到的第一个数字,或者NaN(不是数字),如果没有:

function extractNumber(str) {
  const m = str.match(/-?[0-9]+(\.[0-9]*)?/);
  return m ? Number(m[0]) : NaN;
}

[
  '277.79°K',
  '-8.7°F',
  '+93.4°F',
  '90°F',
  'with prefix 39.5°C',
  '10°K is extremely cold',
  'between 25°C and 29°C',
  'no number'
].forEach(str => {
  console.log(str, '==>', extractNumber(str));
});

输出:

277.79°K ==> 277.79
-8.7°F ==> -8.7
+93.4°F ==> 93.4
90°F ==> 90
with prefix 39.5°C ==> 39.5
10°K is extremely cold ==> 10
between 25°C and 29°C ==> 25
no number ==> NaN

正则表达式的解释:

  • -?-可选的-
  • [0-9]+--1位以上数字
  • (\.[0-9]*)?-.的可选模式,后跟数字

相关问题