Home > database >  Use regex to extract only a decimal number from the beginning of a string
Use regex to extract only a decimal number from the beginning of a string

Time:12-30

Input: "277.79°K" (a string containing a number followed by a character for temperature)

Desired Output: "277.79"

Another example to elaborate the point: Input "-8.7°F" would need to return Output: "-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)

However, when I try .match to actually extract, it says that it has a value of 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. I have tried

CodePudding user response:

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?

CodePudding user response:

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 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:

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]*)? -- optional pattern of ., followed by digits
  • Related