Skip to content
Advertisement

How do I use regex to match on a string that does not contain one of multiple specific words?

How do I use regular expressions to avoid matching strings containing one of multiple specific words?

For example: a string should contain neither the words test, nor sample:

JavaScript

My regular expression is failing in some situations:

JavaScript

In the above two examples:

  1. It has the word test so it worked fine.
  2. It doesn’t have the word test it should be allowed

Is there any way to achieve this?

Advertisement

Answer

You need to use b around the words so they allow matching, ONLY if they are not present as whole words. Try using this,

JavaScript

Also, it is a good idea to make a group as non-capturing, unless you intend to use their value.

Regex Demo

Edit:

For making it case sensitive, enable the i flag by placing i just after / in regex. JS demo,

JavaScript
Advertisement