Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

42
Views
Regex to match a string only inside another string

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.

7 months ago · Santiago Trujillo
3 answers
Answer question

0

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')
)
7 months ago · Santiago Trujillo Report

0

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

7 months ago · Santiago Trujillo Report

0

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.

7 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.