簡體   English   中英

第 1 組正則表達式匹配的 matchAll 數組

[英]matchAll Array for Group 1 Regex Matches

我試圖找出一種方法,將我所有的第 1 組匹配項放入一個數組中,而無需使用帶有matchAll()的循環。

這是我到目前為止所擁有的,但它只產生第一場比賽:

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

如何將matchAll的結果放入一個數組中? 阿卡:

// ABC, ABC

如果您只需要字符串的abc部分,則不需要使用matchAll方法。 只需使用帶有match方法的正后視正則表達式表達式,您就可以輕松獲得想要的結果。

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

以下是有關這些類型的正則表達式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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM