matchAll返回迭代器,需for...of或展开为数组遍历;相比match,它保留捕获组、index、input等完整信息,适合结构化提取;正则必须带g标志,迭代器仅可遍历一次。
matchAll 返回的是一个迭代器,不是数组,不能直接用数组方法(如 map、forEach),需先转成数组或用 for...of 遍历。
match() 在全局正则(带 g 标志)下只返回匹配内容的数组,丢掉捕获组和索引信息;matchAll() 每次返回完整的 RegExpExecArray,包含捕获组、index、input 等,适合需要结构化提取的场景。
match() 的结果无法区分各组,matchAll() 可逐项访问 result[1]、result[2] 等result.index 直接可用matchAll 是唯一选择最常用两种方式:for...of 循环,或展开成数组([...str.matchAll(regex)])。
for...of 更省内存,适合大文本或大量匹配,避免一次性构造整个数组[...iter] 简洁,适合后续要多次使用或链式调用(如 .map()、.filter()).next(),除非手动控制(一般不必要)迭代器只能遍历一次,用完即“耗尽”;重复使用会得到空结果。
立即学习“Java免费学习笔记(深入)”;
const iter = str.matchAll(regex); Array.from(iter); [...iter]; —— 第二个会是空数组g 标志,否则 matchAll 抛错:TypeError: String.prototype.matchAll called with a non-global RegExp
flags: 'gi',确保 g 存在;仅 i 或 u 不行比如从 HTML 片段中提取所有 <p>xxx</p> 的内容:
const html = '<p>Hello</p><p>World</p>';const regex = /<p>(.*?)</p>/g;const matches = [...html.matchAll(regex)];matches.forEach(match => { console.log('全文:', match[0]); // "<p>Hello</p>" console.log('内容:', match[1]); // "Hello" console.log('起始位置:', match.index); // 0 或 13});