[英]matchAll Array for Group 1 Regex Matches
I'm trying to figure out a way to get all my Group 1 matches into an array without using a loop with matchAll()
.我试图找出一种方法,将我所有的第 1 组匹配项放入一个数组中,而无需使用带有
matchAll()
的循环。
Here's what I have thus far, but it only yields the first match:这是我到目前为止所拥有的,但它只产生第一场比赛:
let str = "123ABC, 123ABC"
let results = str.matchAll(/123(ABC)/gi);
let [group1] = results;
alert(group1[1]);
How can I get the results of the matchAll
into one single array?如何将
matchAll
的结果放入一个数组中? Aka:阿卡:
// ABC, ABC
If you only need the abc
part of the string then you don't need to use matchAll
method.如果您只需要字符串的
abc
部分,则不需要使用matchAll
方法。 You can easily get the results you want simply using the positive lookbehind regex expresion with the match
method.只需使用带有
match
方法的正后视正则表达式表达式,您就可以轻松获得想要的结果。
let str = "123ABC, 123ABC" let results = str.match(/(?<=123)ABC/gi); console.log(results) // ["ABC","ABC"]
Here is some more information on these types of regex expressions Lookahead and lookbehind以下是有关这些类型的正则表达式Lookahead 和 Lookbehind 的更多信息
const str = "123ABC, 123ABC" const results = Array.from( str.matchAll(/123(ABC)/gi), ([_, g1]) => g1 ) console.log(results)
您可以使用Array.from
将结果转换为数组并一次性执行映射:
const matches = Array.from(results, match => match[1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.