【发布时间】:2019-10-06 11:08:22
【问题描述】:
来自以下字符串:
Some random text before pattern e-1-e-20-e-3
我想提取“模式前的一些随机文本”和 [1, 20, 3]。
我认为这很简单,并尝试了一些不同的方法,但到目前为止都没有奏效。
这是我的最后一次尝试:
(() => {
const text = 'Some random text --- e-1-e-20-e-3';
const re = /(.*)(?:\-?e\-([0-9]{1,2})\-?)+/g;
const matches = [];
let match = re.exec(text);
while (match != null) {
matches.push(match[1]);
match = re.exec(text);
}
console.log(matches)
})()
前面的返回 ["3"] 我不明白为什么。 我读了: - Getting all subgroups with a regex match - Javascript - Regex access multiple occurrences
我该如何解决这个问题?
编辑:
我变了
我想提取 [1, 20, 3]。
到
我想提取“模式前的一些随机文本”和 [1, 20, 3]。
我想我的问题是,我可以只使用一个正则表达式来做到这一点,还是必须将搜索分成两部分?
【问题讨论】:
-
\d+对于这种情况还不够吗?你能添加规则来选择数字吗?
标签: javascript regex