Reputation: 1620
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:
test
so it worked fine.test
it should be allowedIs there any way to achieve this?
Upvotes: 8
Views: 4554
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.
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
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