JavaScript / ECMAScript

Negative Lookahead in JS

Use negative lookahead `(?!...)` to match words that are NOT in a blocklist (here: log-level keywords).

Try it in the JS tester →

Pattern

regexJS
\b(?!error|warn|debug)[a-z]+\b   (flags: gi)

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("\\b(?!error|warn|debug)[a-z]+\\b", "gi");
const input = "info user login error timeout debug";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));

Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).

How the pattern works

\b is a word boundary. (?!error|warn|debug) is a zero-width assertion that fails if the upcoming text is one of the blocked words. [a-z]+ then matches an actual word. The result: every word EXCEPT error/warn/debug. Lookarounds work in JS and Python; Go's RE2 does NOT support them.

Examples

Input

info user login error timeout debug

Matches

  • info
  • user
  • login
  • timeout

Input

all words except WARN here

Matches

  • all
  • words
  • except
  • here

Input

error error error

No match

Same pattern, other engines

← Back to Negative Lookahead overview (all engines)