Suppose here is a sample text:
Hello this is testing _testisgood _test test ilovetesting again test
The regex
/test/gi
Gives all the test
but I only want the test
string which is surrounded by some other character except space means the opposite of exact match. In other words the test
in testing
, _testisgood
,ilovetesting
i want to match.
Bill's answer is good but may you like this one: just find all words with test and then filter out useless ones;
const s = "Hello this is testing _testisgood _test test ilovetesting again test"
console.log(
(s.match(/[^\s]*test[^\s]*/gi) || []).filter(s => s !== 'test')
)
The regex below will match 'test'
when it either has a non-whitespace character(s) prefixing or post fixing it.
/([^\s]+test[^\s]*|[^\s]*test[^\s]+)/gi;
OR
/(\S+test\S*|\S*test\S+)/gi;
const sentence = "Hello this is testing _testisgood _test test ilovetesting again test";
regex = /([^\s]+test[^\s]*|[^\s]*test[^\s]+)/gi;
console.log(sentence.match(regex));
You can match just _testisgood
and ilovetesting
in your example by specifying one or more characters that are not whitespace before and after test
, like this:
/[^\s]+test[^\s]+/gi
If you also want to match testing
, then drop [^\s]+
from the beginning of the pattern.