← 中文资源

简体中文版本

RegExp d 标志报告匹配区间

开启 hasIndices 的 d 标志后,匹配结果会给出整体与每个捕获组的起止下标。

阅读英文原文

实现说明

迭代发生在 for (let i = 1; i < match.length; i += 1) 内部——循环之外的语句只执行一遍。 顶层就这几处状态:pattern、match、named、plain。

使用要点

  • 每一步打印都带着自己的标签:full:、indices:、group。

常见问题

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。 跨调用保留的状态放在这些顶层绑定里:pattern、match、named。

核心语句

const match = pattern.exec('released 2026-11-17');
for (let i = 1; i < match.length; i += 1) {
  const [start, end] = match.indices[i];
  console.log('group', i, '->', match[0].slice(start - match.index, end - match.index));
}

代码示例

// d flag (hasIndices): match.indices records spans
const pattern = /(\d{4})-(\d{2})-(\d{2})/d;
const match = pattern.exec('released 2026-11-17');

if (match) {
  console.log('full:', match[0]);
  console.log('indices:', match.indices[0]);
  for (let i = 1; i < match.length; i += 1) {
    const [start, end] = match.indices[i];
    console.log('group', i, '->', match[0].slice(start - match.index, end - match.index));
  }
}

// 命名分组同样记录区间
const named = /(?<year>\d{4})-(?<month>\d{2})/d.exec('2026-11');
console.log('year range:', named.indices.groups.year);
console.log('month text:', named.groups.month);

// 没有 d 标志时 indices 为 undefined
const plain = /x/.exec('x');
console.log('plain has indices:', plain.indices !== undefined);