RegExp Named Groups Drive exec Loops

Iterate global regexes with a while-exec loop typed as RegExpExecArray | null, reading named groups and tracking lastIndex across matches.

TypescriptData Integrity

Code

typescriptsnippet
24 lines
// 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);

What the code does

The loop while (match !== null) is the only repeated construct.

The whole flow works on the top-level bindings: record, input, match.

What to watch for

  • No dependencies section needed; the standard library is the whole story.

Using it

The run prints consumed up to: after each match, then closes with final exec: showing the terminating null and restart exec: re-matching from index 0.

Key statements

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);
}

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `record`, `input`.