Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
Select specific Text between two strings (multiline)

I want to Select specific text between two strings using regex.

e.g:

foo I have four toys bar    //single line

foo     //multiline
I
have
four
toys
bar

foo I have three pets bar

foo
I
have
three
pets bar

How to select text between "foo" and "bar" with specific word containing "four"

Output:

I have four toys

I
have
four
toys

My code:

foo[\s\S]*?(four)[\s\S]*?bar

My code is working fine but problem is that when when "four" word does not comes between "foo" and "bar" it is selecting all text till "four" word

foo I have three pets bar

foo I have four toys bar

foo
I
have
three
pets bar

I just want text between "foo" and "bar" when it is containg specific word "four"

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

We can use the following regex pattern, in dot all mode:

\bfoo\s+(?:(?!\bbar\b).)*?\s+four\s+(?:(?!\bfoo\b).)*?\s+bar

var input = `foo I have four toys bar

foo
I
have
four
toys
bar

foo I have three pets bar

foo
I
have
three
pets bar`;

var matches = input.match(/\bfoo\s+(?:(?!\bbar\b).)*?\s+four\s+(?:(?!\bfoo\b).)*?\s+bar/gs)
                   .map(x => x.replace(/^foo\s+|\s+bar$/g, ""));
console.log(matches);

An explanation to this complex regex pattern might be helpful here:

\bfoo\s+            match 'foo' followed by one or more whitespace characters
(?:(?!\bbar\b).)*?  match any content WITHOUT encountering 'bar'
\s+four\s+          match 'four' surrounded by whitespace
(?:(?!\bfoo\b).)*?  match any content WITHOUT encountering 'foo'
\s+bar              whitespace followed by ending 'bar'

Note that due to the way match() behaves, we also have a map step where we strip off leading foo and ending bar from every match.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!