RegExp Lookbehind Matches Context

Positive and negative lookbehind anchor matches to preceding text without including it, so key prefixes and price signs stay out of captured values.

JavascriptData Integrity

Code

javascriptsnippet
21 lines
// Lookbehind assertions anchor a match to what came before, without
// including that context in the result.
const rows = 'ok:200 err:500 ok:201 err:503';

// Positive lookbehind: codes that directly follow "ok:"
const okCodes = rows.match(/(?<=ok:)\d{3}/g);
console.log('ok codes:', okCodes);

// Negative lookbehind: codes NOT directly preceded by "ok:"
const errorCodes = rows.match(/(?<!ok:)\d{3}/g);
console.log('error codes:', errorCodes);

// Mention extraction: @names preceded by whitespace, skipping email domains
const chat = 'Mentions: @ada @grace — email [email protected] is not a mention';
const mentions = [...chat.matchAll(/(?<=\s)@(\w+)/g)].map((m) => m[1]);
console.log('mentions:', mentions);
console.log('email domain skipped:', !mentions.includes('example'));

// Negative lookbehind can exclude prices while keeping bare numbers
const tags = 'CPU $299 GPU $399 case 89';
console.log('unprefixed:', tags.match(/(?<!\$)\b\d+\b/g));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ok codes: [ '200', '201' ]
error codes: [ '500', '503' ]
mentions: [ 'ada', 'grace' ]
email domain skipped: true
unprefixed: [ '89' ]

Inside the snippet

Demo state sits in top-level bindings: rows, okCodes, errorCodes, chat.

Points of care

  • No package installation, no environment variables, no setup steps.

Putting it to use

The run emits 5 labeled sections — ok codes:, error codes:, mentions:, email domain skipped:, unprefixed: — one per step.

Core lines under the microscope

const mentions = [...chat.matchAll(/(?<=\s)@(\w+)/g)].map((m) => m[1]);

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. Its state lives in module-level bindings: `rows`, `okCodes`, `errorCodes`.