【问题标题】:How can I extract each integer or float (positive or negative) from a string in js如何从js中的字符串中提取每个整数或浮点数(正数或负数)
【发布时间】:2021-03-24 21:25:26
【问题描述】:

这是我的代码。它仍然返回null,我不知道为什么!

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));

【问题讨论】:

标签: javascript arrays string numbers floating


【解决方案1】:

您的正则表达式很好,您只需将其设置为字符串而不是正则表达式文字。

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

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

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

编辑:

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

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

【讨论】:

  • 谢谢它的工作,但是我没有得到我想要的我认为我的正则表达式不正确......
  • 我得到:['18.56',索引:0,输入:'18.56-5.45-3.78',组:未定义]
  • 是的,这是一个“匹配对象”,尝试在末尾添加 [0] 以引用匹配的字符串。
【解决方案2】:

你需要

  • 不引用正则表达式 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)

【讨论】:

    【解决方案3】:

    使用正则表达式(不是字符串)作为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));

    【讨论】:

      猜你喜欢
      • 2019-03-16
      • 2022-10-16
      • 1970-01-01
      • 2019-02-01
      • 2019-12-07
      • 1970-01-01
      • 2018-11-26
      • 2017-06-29
      • 1970-01-01
      相关资源
      最近更新 更多