matchAll 是 ES2020 引入的方法,用于一次性获取正则在字符串中所有匹配的完整详情(含捕获组),返回可迭代对象,需带 g 标志,否则抛出 TypeError;遍历时每个结果为带 index、groups 等属性的数组。

matchAll 是 ES2020 引入的方法,专门用于**一次性获取正则表达式在字符串中所有匹配结果的完整详情(含捕获组)**,返回一个可迭代对象(RegExpStringIterator),每个迭代项是一个类似 match() 返回的数组,但带有 index 和 groups 属性。
确保正则使用全局标志 g
这是前提。没有 g 标志,matchAll 会抛出 TypeError。
✅ 正确:
/(\d+)-(\w+)/g、/(?<year>\d{4})-(?<month>\d{2})/g</month></year>
❌ 错误:
/(\d+)-(\w+)/(缺 g)
遍历 matchAll 返回的迭代器,解构每轮匹配
每次迭代得到一个 result 数组,它:
- 索引
0是完整匹配字符串 - 索引
1、2… 是按顺序的捕获组内容(含命名捕获组值) - 带额外属性:
.index(匹配起始位置)、.groups(命名捕获组对象)、.input(原字符串)
示例:
const text = "ID: 123-abc, then 456-def";<br>const regex = /(\d+)-(\w+)/g;<br><br>for (const match of text.matchAll(regex)) {<br> console.log({<br> full: match[0], // "123-abc", "456-def"<br> num: match[1], // "123", "456"<br> word: match[2], // "abc", "def"<br> index: match.index, // 4, 16<br> groups: match.groups // undefined(无命名组)<br> });<br>}
用命名捕获组提升可读性
配合 ?<name></name> 语法,match.groups 会直接提供结构化对象:
const regexNamed = /(?<id>\d+)-(?<tag>\w+)/g;<br>for (const m of text.matchAll(regexNamed)) {<br> console.log(m.groups); // { id: "123", tag: "abc" }<br> console.log(m.index); // 4<br>}
转为数组或用展开语法收集全部结果
若需多次使用或链式处理,可立即转成数组:
const allMatches = [...text.matchAll(regex)];<br>// each item is a full match array with index/groups<br>console.log(allMatches[0][1]); // 第一次匹配的第一个捕获组
注意:这会一次性加载所有匹配到内存,对超大文本或海量匹配需谨慎。

















