← 中文资源

简体中文版本

命名分组驱动 exec 循环

用 while-exec 循环遍历全局正则:匹配结果类型是 RegExpExecArray | null,命名分组带类型提示,lastIndex 随每次匹配推进、耗尽后归零。

阅读英文原文

实现说明

在这里做循环的是 while (match !== null)。 各个操作都建立在顶层绑定之上:record、input。

使用要点

  • 演示输出是带标签的(consumed up to:、final exec:、restart exec:),每个操作都会留下自己的一行标注。

常见问题

包管理器会看到什么?

一份空的依赖清单。示例没有需要抓取的导入。 文件的状态由几个模块级绑定持有:record、input。

核心语句

match = record.exec(input);

代码示例

// Named groups make exec results self-describing; exec drives the loop
const record = /(?<key>[a-z]+)=(?<value>\d+)/g;
const input = 'color=3 frame=60 level=12';

// RegExpExecArray | null is the loop type: every access is guarded
let match: RegExpExecArray | null = record.exec(input);
const settings: Array<{ key: string; value: number }> = [];

while (match !== null) {
  settings.push({
    key: match.groups?.key ?? 'unknown',
    value: Number(match[2]),
  });
  console.log('consumed up to:', record.lastIndex);
  match = record.exec(input);
}

console.log(settings);

// The terminating call returns null and resets lastIndex to 0
console.log('final exec:', match, 'lastIndex reset to:', record.lastIndex);

// Calling exec again restarts the scan from index 0: fresh pass, fresh match
console.log('restart exec:', record.exec(input), 'lastIndex:', record.lastIndex);