Dave Bernhard

Web Developer

📚 Reading: The Riddle-Master of Hed by Patricia A. McKillip

Snippet

Regex to match a string that doesn't contain a string

Negative lookahead ftw


🔥 Bonfire|First lit on July 13
2 min read

Regex can be really powerful, but remember that it comes in different flavours, can be difficult to decipher, and has its limitations.See, for example, this incredible answer on Stack Overflow about matching HTML tags with regex

One powerful feature is the negative lookahead, using the ?! syntax. When combined with .*, we can check that a pattern is not contained anywhere in a string:

/^(?!.*(JavaScript|TypeScript))/.test(
    'I love all the parentheses in Lisp'
) // true => string does not contain "JavaScript" or "TypeScript"

/^(?!.*(JavaScript|TypeScript))/.test(
    'It looks like JavaScript is on its way out'
) // false

If you want to test for the presence of one pattern, but the absence of another, you can use the .* syntax again. The following will match strings containing John, that don't also contain Yoko:

/^(?!.*Yoko).*John/.test(
    'John and Yoko were both artists'
) // false => string contains Yoko

/^(?!.*Yoko).*John/.test(
    'I wonder what John would have thought of the internet'
) // true => string contains John, but not Yoko