首页 > 解决方案 > 正则表达式从字符串中提取两个带空格的数字

问题描述

我对简单的 rexex 有问题。我有示例字符串,例如:

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

我想从字符串中提取这些数字。所以从第一个例子开始,我需要两组:649670。从第二个例子:42 03642 896Then I will remove space.

目前我有这样的事情:

\d+ ?\d+

但这不是一个好的解决方案。

标签: javascriptregex

解决方案


您可以使用

\n\d+(?: \d+)?
  • \n- 匹配新行
  • \d+- 一次或多次匹配 0 到 9 的数字
  • (?: \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)))


推荐阅读