matchAll 在创建迭代器时复制 lastIndex。用日志 ID 的最小示例演示为什么遍历前把原正则归零已经太晚,以及怎样让整行扫描从头开始。
重置 lastIndex 后,为什么 matchAll 还是漏了第一项?
作者:小括号
时间:2026-12-02
浏览:500
文章目录
如果先用 exec() 从一行日志里取第一个 ID,再用 matchAll() 收集所有 ID,结果里会少一项。即使在遍历前把 lastIndex 清零,结果也还是从第二个 ID 开始,因为迭代器已经拿到了当时的搜索起点。
第一次匹配把起点留在了哪里
带 g 的正则用 exec() 找到 id=12 后,lastIndex 变成 5,正好指向第一个空格。下一轮从这个空格往后找,直到下标 6 才遇到 id=34。

{
const text = 'id=12 id=34 id=56';
const token = /id=(\d+)/g;
const first = token.exec(text);
console.log('exec:', first[1], 'lastIndex:', token.lastIndex);
const matches = text.matchAll(token);
console.log('matchAll:', Array.from(matches, match => match[1]).join(', '));
console.log('original lastIndex:', token.lastIndex);
}

调用 matchAll(token) 时,迭代器内部的正则会复制 token 当时的 lastIndex。随后 Array.from() 遍历迭代器,推进的是内部正则,所以第一项是 34,遍历结束后 token.lastIndex 仍是 5。
要归零,就在创建迭代器之前
下面先把迭代器存到 tail,再把 token.lastIndex 设成 0。展开 tail 时仍然只有 34 和 56。同一行日志交给 collectIds(),则会得到 12、34 和 56。
{
const text = 'id=12 id=34 id=56';
const token = /id=(\d+)/g;
token.exec(text);
const tail = text.matchAll(token);
token.lastIndex = 0;
function collectIds(line) {
return Array.from(line.matchAll(/id=(\d+)/g), match => match[1]);
}
console.log('saved iterator:', Array.from(tail, match => match[1]).join(', '));
console.log('full scan:', collectIds(text).join(', '));
}

collectIds() 每次执行均实例化新的全局正则,其 lastIndex 默认为 0,故能完整收集三个 ID。映射回调通过 match[1] 提取首个捕获组,仅保留数字内容。
需要复用同一个正则时,先把 token.lastIndex 设为 0,再调用 matchAll() 创建新的迭代器。遇到漏项,我会先在这次调用的前一行打印 lastIndex,再对照结果的第一项。
实用工具推荐
电子包浆
使用 ›绿化、压缩、噪点和虚拟水印,自由调节做旧程度。
图片压缩
使用 ›选择画质和输出格式,预览压缩前后的大小。
作者最新文章
相关文章