如何在 JavaScript 中使用捕獲組擷取正則表達式的所有結果

我面臨了這樣的任務 基本上,我有一個包含多個URL的字符串,我想使用正則表達式處理它們。 這個正則表達式使用了捕獲組,非常方便。 那麼,讓我們從獲取單個結果開始: const text = 'hello1 bla bla hello2' const regex = /hello\d/ text.match(regex) /* [ 'hello1', index: 0, input: 'hello1 bla bla hello2', groups: undefined ] */ 使用 g標誌可以從正則表達式中獲取多個結果,而且這是自動進行的,但現在 match() 的結果不同,只返回匹配的結果: const text = 'hello1 bla bla hello2' const regex = /hello\d/g console.log(text.match(regex)) //[ 'hello1', 'hello2' ] 使用 ES2020中的 matchAll() 方法可以獲得更詳細的結果集。 該方法返回一個迭代器對象,所以需要使用循環來遍歷結果: for (let match of text.matchAll(regex)) { console.log(match) } /* [ 'hello1', index: 0, input: 'hello1 bla bla hello2', groups: undefined ] [ 'hello2', index: 15, input: 'hello1 bla bla hello2', groups: undefined ] */ 現在讓我們談談捕獲組。...