实现说明
在这里做循环的是 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);