Abhiram
Abhiram

Reputation: 1620

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?

Upvotes: 8

Views: 4554

Answers (2)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

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)))

Upvotes: 9

RK_15
RK_15

Reputation: 939

Try this regex (Word boundry '\b' is necessary and also arbitrary number of characters can be present before those sample words):

/^(?!.*?\b(sample|test)\b)/

it will match the empty string too because that doesn't contain sample or test word. To check if the string must not be empty and doesn't contain sample and test word then use :

/^(?!.*?\b(sample|test)\b).+?/

Upvotes: 1

Related Questions