首页 > 解决方案 > 使用匹配将正则表达式解析为本地变量

问题描述

我有这些任务:

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

任何人都可以提出一种更简洁的解析方式吗?

标签: javascriptregex

解决方案


Javascript 的字符串replace成员方法允许您用字符串替换正则表达式。将 1 个或多个不是数字的任何字符全局替换为空格。然后使用字符串split成员方法在空间上解析结果,然后将这 5 个标记分配给this.id, x, y, width, height

const [this.id, x, y, width, height] = line.replace(/[^\d]+/g, ' ').split(' ');

推荐阅读