John Brew
John Brew

Reputation: 31

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"

Upvotes: 1

Views: 97

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522626

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.

Upvotes: 0

Related Questions