javascript - 使用匹配将正则表达式解析为本地变量
问题描述
我有这些任务:
const [x, y] = line.match(/\d+,\d+/g, line)[0].split(',');
const [width, height] = line.match(/\d+x\d+/g, line)[0].split('x');
this.id = line.match(/^#\d+/g, line)[0].split('#')[1];
当解析这样的一行文本时:
#1 @ 265,241: 16x26
任何人都可以提出一种更简洁的解析方式吗?
解决方案
Javascript 的字符串replace
成员方法允许您用字符串替换正则表达式。将 1 个或多个不是数字的任何字符全局替换为空格。然后使用字符串split
成员方法在空间上解析结果,然后将这 5 个标记分配给this.id
, x
, y
, width
, height
。
const [this.id, x, y, width, height] = line.replace(/[^\d]+/g, ' ').split(' ');
推荐阅读
- linux - 文件名包含特定字符串的远程 SSH 复制文件
- uwp - TabView suddenly missing from UWP
- c# - C++ 到 C# 实现
- kotlin - Taking sequence elements fulfilling a predicate then continuing from there in Kotlin
- reactjs - 卸载组件时 React Router v4 替换历史记录
- javascript - 仅接受字母的文本框功能不起作用
- c# - 一起使用 SQLiteConnection 和 SQLiteAsyncConnection
- c# - 列表参数的对象名称在 ForEach 循环之外以 @ 为前缀
- python - 如何使用时间戳 Python 剪切(`trim`)音频
- python-3.x - 如何使用 AWS CDK 将阶段变量传递给 api 网关中的 lambda 函数?