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.
Code
// 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 ada@example.com 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
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.