javascript - 正则表达式从字符串中提取两个带空格的数字
问题描述
我对简单的 rexex 有问题。我有示例字符串,例如:
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+
但这不是一个好的解决方案。
解决方案
您可以使用
\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)))
推荐阅读
- java - 弹簧上下文不加载
- windows - 在服务器上安装 SSL 证书后,Google Chrome 中的数据呈现缓慢
- css - 将flexbox的子元素与第二个flexbox的子元素对齐?
- amazon-web-services - 火花。在 aws s3a 存储上写入大文件时出现问题
- javascript - 从数组中的 python-shell 捕获消息
- button - 如何在 SwiftUI 中将图像设置为按钮?
- contactless-smartcard - 解析 EMV 9F10 令牌
- python - 从 2D 坐标生成 3D 曲面图
- c# - LeetCode:使用 HashSet 找到总和为 0 的 Triplet
- javascript - 如何安装 react-bootstrap v0.32.4?