Lesson 6 of 13 · 20m
Lookarounds: Matching on Context Without Consuming It
Lookahead and lookbehind as zero-width assertions, engine support differences, and when a lookaround is cleverness you should replace with code.
Lookarounds let a pattern ask "what's next to me?" without putting the answer in the match. They're the strongest construct in Perl-style regex and the most abused. Used well they make a replacement surgical. Used badly they turn a validation rule into an unreadable wall nobody dares touch.
Four assertions, zero width
X(?=Y)— positive lookahead: X, only if followed by YX(?!Y)— negative lookahead: X, only if not followed by Y(?<=Y)X— positive lookbehind: X, only if preceded by Y(?<!Y)X— negative lookbehind: X, only if not preceded by Y
"Zero-width" is the entire idea: the engine checks the condition, then returns to the exact position it started from. Nothing is consumed and nothing lands in match[0].
The cursor doesn't move
const withCommas = n => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
console.log(withCommas(1234567)); // 1,234,567
console.log(withCommas(999)); // 999Read it as "a non-word-boundary position followed by groups of exactly three digits, followed by a non-digit." The match is an empty string at each insertion point; the replacement drops a comma there. A good party trick. In production, new Intl.NumberFormat("en-US").format(n) does the same job and also knows India groups digits as 12,34,567 — your regex does not.
Lookbehind for surgical replacement
const log = "POST /login user=alice password=hunter2&remember=1";
console.log(log.replace(/(?<=password=)[^&\s]+/g, "[REDACTED]"));
// POST /login user=alice password=[REDACTED]&remember=1Without lookbehind you'd capture password= and re-insert it with $1. The lookbehind version states intent directly: replace the value, keep the key.
Negative lookahead: the exclusion case
const files = ["app.js", "app.min.js", "vendor.js", "vendor.min.js"];
console.log(files.filter(f => /^(?!.*\.min\.js$).+\.js$/.test(f)));
// ["app.js", "vendor.js"] — .js files that don't end in .min.js(?!.*\.min\.js$) asserts "this position is not followed by a string ending in .min.js." Readable enough at one lookahead. Three lookaheads deep it becomes the password-policy wall below.
The other classic is "match X only when not preceded by Y" — (?<!\\)% matches a percent sign that wasn't escaped, and (?<!https?:)// catches protocol-relative links. These work because the assertion inspects raw context, not grammar.
Support varies more than anything else in the spec
- JavaScript (ES2018+): arbitrary-length lookbehind —
(?<=Bearer\s+)\S+works. - Python
re: lookbehind must be fixed width; that pattern raisesre.error: look-behind requires fixed-width pattern. The third-partyregexmodule relaxes this. - PCRE2 and Java: bounded-length lookbehind —
\s{1,3}yes,\s+no. - RE2, Go,
grep -E, ripgrep's default engine, Prometheus: no lookarounds at all. Reach forgrep -Porrg -P.
The password-policy trap
^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[^\w\s]).{12,64}$It works, and it's bad engineering. The user gets one "invalid password" instead of "add a digit"; each (?=.*X) rescans the input from position zero; and NIST SP 800-63B discourages composition rules entirely in favor of length plus breach-list screening. Four separate test() calls give you per-rule error messages, faster failure, and code your successor can read.
Overlapping matches with a lookahead wrapper
console.log([..."ababa".matchAll(/(?=aba)/g)].length); // 2 — positions 0 and 2Because the lookahead consumes nothing, matchAll advances one position per match. Wrapping a pattern in (?=...) is the standard way to count overlapping occurrences — and a good demonstration of why zero-width constructs behave differently from everything else in the engine.
Field notes
- Lookarounds are atomic in Perl-style engines: once satisfied, the engine never backtracks inside them. Captures inside a lookahead freeze at first success.
- "Lines not containing X" is
grep -v X, not^(?!.*X).*$. Pipeline beats pattern. - Because nothing is consumed, lookarounds match at overlapping positions — great for counting overlaps, surprising everywhere else.
- If a pattern needs three lookaheads to express a business rule, it wants to be three lines of code.
Keep reading
Related articles from the SudoSecurity blog.
Java Pulled Primitive Patterns After Five Previews. JDK 28 Won't Compile Them.
Primitive types in patterns, instanceof, and switch previewed in every JDK from 23 to 27. On November 9 the Amber team withdrew the feature, and it won't be in JDK 28 even with --enable-preview. Here's why Valhalla changed the plan, what replaces it, and how to rewrite code that used it.
.NET 11 Is Out. Union Types Got the Applause, but unsafe Is What Changed.
.NET 11 shipped on November 10, 2026, and C# 15 finally has union types, the feature people have asked for since pattern matching arrived.
PHP 8.6 Finally Turns On the Session Settings You Were Told to Set in 2006
Every PHP hardening guide for two decades has told you to flip the same three session settings. PHP 8.6, due November 19, 2026, flips them for you: strict mode on, HttpOnly on, SameSite set to Lax.
Rust 1.100: The Never Type Is Finally Stable, and Cargo Learned to Wait
Rust 1.100 stabilizes the never type after ten years and five failed attempts, along with the core Allocator API and a DropGuard helper. The change most teams will notice is in Cargo: a one-line config that makes it skip any crate version published in the last few days.