← 中文资源

简体中文版本

sticky 正则按 lastIndex 游标切分

y(sticky)标志把正则锚定在 lastIndex:匹配不上就地失败而不跳过,配合手动维护的游标做词法切分,非法字符立刻暴露精确位置,g 标志则适合全量扫描。

阅读英文原文

实现说明

全部逻辑都在函数 nextToken、tokenize中。 在这里做循环的是 while (pos < input.length)。

使用要点

  • 跑完文件,输出里会留下标记——illegal char at index、tokens:、g skips:。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 nextToken、tokenize。

签名一览:function nextToken(input, pos)

核心语句

return match ? { value: match[1], end: token.lastIndex } : { value: null, end: pos };
const match = token.exec(input);

代码示例

// The y (sticky) flag anchors the regex at lastIndex: it must match there,
// failing outright instead of skipping characters - ideal for lexing from a fixed cursor
const spaces = /\s+/y;
const token = /(\d+|[a-zA-Z_]\w*|[+\-*/()])/y;

function nextToken(input, pos) {
  spaces.lastIndex = pos;
  const ws = spaces.exec(input);
  if (ws) pos = spaces.lastIndex; // consume whitespace first so the cursor lands on real content
  token.lastIndex = pos;
  const match = token.exec(input);
  return match ? { value: match[1], end: token.lastIndex } : { value: null, end: pos };
}

function tokenize(input) {
  const found = [];
  let pos = 0;
  while (pos < input.length) {
    const hit = nextToken(input, pos);
    if (!hit.value) {
      console.log('illegal char at index', hit.end, JSON.stringify(input[hit.end]));
      break;
    }
    found.push(hit.value);
    pos = hit.end; // after a match, lastIndex sits at the end of the match
  }
  return found;
}

console.log('tokens:', tokenize('12 + count * (3 - x)').join(' | '));
console.log('tokens:', tokenize('10 ? bad').join(' | '));

// Contrast: with the g flag a failed match skips ahead and keeps searching, y does not - g suits full scans,
// y suits token-by-token parsing where illegal input exposes its position immediately
console.log('g skips:', 'ab12cd34'.match(/\d+/g).join(','));
token.lastIndex = 3;
console.log('y refuses non-matching index:', token.exec('3+4=7') === null);