简体   繁体   English

使用正则表达式从字符串的开头仅提取一个十进制数

[英]Use regex to extract only a decimal number from the beginning of a string

Input: "277.79°K" (a string containing a number followed by a character for temperature)输入: “277.79°K” (一个包含数字后跟温度字符的字符串)

Desired Output: "277.79"期望 Output: “277.79”

Another example to elaborate the point: Input "-8.7°F" would need to return Output: "-8.7"另一个详细说明这一点的例子:输入"-8.7°F"需要返回 Output:“-8.7 "-8.7"

What I have tried: I have tried using a regex我试过什么:我试过使用正则表达式

let pattern = /^[0-9]*\.?[0-9]*$/
let num = pattern.test("277.79°K")

This will return true or false to confirm that I have the type of positive number that I am looking for (haven't gotten something to work for negative numbers)这将返回 true 或 false 以确认我有我正在寻找的正数类型(还没有得到用于负数的东西)

However, when I try.match to actually extract, it says that it has a value of null.但是,当我 try.match 实际提取时,它说它的值为 null。

thenum = "277.79°K".match(/^[0-9]*\.?[0-9]*\n/) //returns null

Edit: I am getting closer and have this code that can extract the number if it has a space following it, but NOT if the degree or letter immediately follows the number without a space.编辑:我越来越近了,有了这段代码,如果数字后面有空格,它可以提取数字,但如果学位或字母紧跟在数字后面没有空格,则不能。

let rx1 = /( |^)([+-]?[0-9]*\.?[0-9]*)( |$)/g
temp = rx1.exec('-277.79 °K') //returns ['-277.79 '...]
temp = rx1.exec('-277.79°K') //returns null

Therefore Main Problem: I can get a test for true/false to work but I can't successfully write a function that extracts just the part I need out of the string.因此,主要问题:我可以测试 true/false 是否正常工作,但我无法成功编写仅从字符串中提取我需要的部分的 function。 I have tried我试过了

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

did you want this effect?你想要这种效果吗?

So you want to extract the number, not just match.所以你想提取数字,而不仅仅是匹配。 Here is a function that extracts the first number it finds, or NaN (not a number) if none:这是一个 function 提取它找到的第一个数字,如果没有则提取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)); });

Output: Output:

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

Explanation of regex:正则解释:

  • -? -- optional - -- 可选-
  • [0-9]+ -- 1+ digits [0-9]+ -- 1+ 位
  • (\.[0-9]*)? -- optional pattern of . - 的可选模式. , followed by digits , 后跟数字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM