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:

^((?!(sample|test)).)*$

My regular expression is failing in some situations:

1. this is a test case 
2. this is a testing area 

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,

^(?:(?!b(sample|test)b).)*$

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,

var arr = ['this is a test case','this is a testing area','this is a Test area']

arr.forEach(s => console.log(s + " --> " + /^(?:(?!b(sample|test)b).)*$/i.test(s)))
Advertisement