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
x
2
1
^((?!(sample|test)).)*$
2
My regular expression is failing in some situations:
JavaScript
1
3
1
1. this is a test case
2
2. this is a testing area
3
In the above two examples:
- It has the word
test
so it worked fine. - 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
1
2
1
^(?:(?!b(sample|test)b).)*$
2
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,
JavaScript
1
3
1
var arr = ['this is a test case','this is a testing area','this is a Test area']
2
3
arr.forEach(s => console.log(s + " --> " + /^(?:(?!b(sample|test)b).)*$/i.test(s)))