Sticky Regex y Flag Anchors At lastIndex

The sticky y flag anchors a regex at lastIndex so failed matches abort instead of skipping ahead, making it the right tool for cursor-based tokenizing.

JavascriptData Integrity

Code

snippet
// 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);

What the code does

Sticky Regex y Flag Anchors At lastIndex reduces to the functions nextToken and tokenize.

Repetition is confined to while (pos < input.length) — the rest of the file is straight-line.

Using it

The entry-point signature is function nextToken(input, pos)

The run emits 4 labeled sections — illegal char at index, tokens:, g skips:, y refuses non-matching index: — one per step.

Key statements

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

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `nextToken`, `tokenize` at load time.