Home > Back-end >  Regex to match a string only inside another string
Regex to match a string only inside another string

Time:12-25

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.

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

The regex below will match 'test' when it either has a non-space character(s) prefixing or post fixing it.

/([^\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));

  • Related