代码之家  ›  专栏  ›  技术社区  ›  Greggy

正则表达式从字符串中提取两个带空格的数字

  •  0
  • Greggy  · 技术社区  · 6 年前

    Something1\sth2\n649 sth\n670 sth x
    Sth1\n\something2\n42 036 sth\n42 896 sth y
    

    我想从字符串中提取这些数字。所以从第一个例子来看,我需要两组人: 649 670 42 036 42 896 Then I will remove space .

    目前我有这样的东西:

    \d+ ?\d+
    

    2 回复  |  直到 6 年前
        1
  •  2
  •   Code Maniac    6 年前

    你可以用

    \n\d+(?: \d+)?
    
    • \n -匹配新行
    • \d+
    • (?: \d+)? -匹配空格后接数字一个或多个时间。( ? 可选)

    let strs = ["Something1\sth2\n649 sth\n670 sth x","Sth1\n\something2\n42 036 sth\n42 896 sth y"]
    
    let extractNumbers = str => {
      return str.match(/\n\d+(?: \d+)?/g).map(m => m.replace(/\s+/g,''))
    }
    
    strs.forEach(str=> console.log(extractNumbers(str)))
        2
  •  0
  •   Morphyish    6 年前

    如果你需要移除空格。那么最简单的方法就是删除空格,然后使用2个不同的regex废弃数字。

    str.replace(/\s+/, '').match(/\\n(\d+)/g)
    

    首先,使用 \s 带有 + replace

    \\n(\d+) .

    regex的第一部分帮助我们确保没有捕获不在新行后面的数字,使用 \ 逃离 \ \n .

    (\d+) 是实际的匹配组。

        3
  •  0
  •   emonn    6 年前

    var str1 = "Something1\sth2\n649 sth\n670 sth x";
    var str2 = "Sth1\n\something2\n42 036 sth\n42 896 sth y";
    var reg = /(?<=\n)(\d+)(?: (\d+))?/g;
    var d;
    while(d = reg.exec(str1)){
        console.log(d[2] ? d[1]+d[2] : d[1]);
    }
    console.log("****************************");
    while(d = reg.exec(str2)){
        console.log(d[2] ? d[1]+d[2] : d[1]);
    }