如何从js中的字符串中提取每个整数或浮点数(正数或负数)

How can I extract each integer or float (positive or negative) from a string in js

这是我的代码。它仍然 returns 为空,我不知道为什么!

var tName = "18.56x^2   -   5.45x  -3.78";
abc = tName.replace(/x/g, "").replace("^2", "").replace(/\s/g, "");
console.log(abc);

$re = "/-?\d+(?:\.\d+)?/m";
$str = abc.toString();
console.log($str.match($re));

你的正则表达式没问题,你只需将它设置为字符串而不是正则表达式文字。

当您构建 RegExp 常量时,您想要使用 RegExp() 构造函数(用于从字符串构建)或只是一个正则表达式文字。您目前正在构建一个普通字符串,看起来 像一个正则表达式,但实际上不是。

尝试将此行编辑为以下内容:

$re = /-?\d+(?:\.\d+)?/m;

编辑:

要访问字符串本身,您只需使用索引 0。

var mat = $str.match($re);
console.log(mat[0])

像这样使用正则表达式(不是字符串)作为 String.prototype.match() 的参数:

var tName = "18.56x^2   -   5.45x  -3.78";
abc = tName.replace(/x/g, "").replace("^2", "").replace(/\s/g, "");

$re = /-?\d+(?:\.\d+)?/m;
$str = abc.toString();
console.log($str.match($re));

你需要

  • 不引用正则表达式 AND
  • 不转义\d AND
  • 添加全局标志

试试这个

const $re = /-?\d+(?:\.\d+)?/mg,
      tName = "18.56x^2   -   5.45x  -3.78",
      abc = tName.replace(/x/g, "").replace("^2", "").replace(/\s/g, ""),
      nums = [...abc.matchAll($re)].map(m => m[0]);
console.log(abc)
console.log(nums)