第1组正则表达式匹配的matchAll数组

问题描述 投票:0回答:2

[我正在尝试一种方法,以将我所有的第1组匹配项放入一个数组中,而不使用带有matchAll()的循环。

这是我到目前为止的内容,但只产生第一个匹配项:

let str = "123ABC, 123ABC"
let results = str.matchAll(/123(ABC)/gi);
let [group1] = results;
alert(group1[1]);

如何将matchAll的结果分成一个数组?又名:

// ABC, ABC
javascript arrays regex prototype iterable
2个回答
0
投票

您可以使用Array.from将结果转换为数组并一次性执行映射:

const matches = Array.from(results, match => match[1])

0
投票

如果只需要字符串的abc部分,则不需要使用matchAll方法。只需使用match方法使用positive lookbehind正则表达式即可轻松获得所需的结果。

let str = "123ABC, 123ABC"
let results = str.match(/(?<=123)ABC/gi);
console.log(results)
// ["ABC","ABC"]

这里是有关这些类型的正则表达式的更多信息Lookahead and lookbehind


0
投票

© www.soinside.com 2019 - 2024. All rights reserved.