Saif
Saif

Reputation: 7042

regex to catch every thing between occurrences of a word

I want a regex to catch everything inside occurrences of a specific word say hello. left inclusive and right exclusive. hello all everything hello eve will give hello all everything and hello eve.

I am using hello.*(?=hello) using reference from Here, see Demo. But it only match once and i tried some possibility no luck. Is it possible?

input:

hello i am xyz lol hello i
am abc ..;sda<>
hello
i am pqr ahe kiop hello
abc axyz
no
yes 
hepdd
jol
hello
podjkd
dasfh

output expected:

1:hello i am xyz lol

2:hello i
am abc ..;sda<>

3:hello
i am pqr ahe kiop

4:hello
abc axyz
no
yes 
hepdd
jol

5:hello
podjkd
dasfh

Upvotes: 1

Views: 84

Answers (1)

anubhava
anubhava

Reputation: 784998

You need to use s (DOTALL) flag with this regex:

/(hello.*?)(?=hello|\z)/gmsi

RegEx Demo

  • \z will match last character in multiline text.
  • s will match newline as well while using .*?
  • Use .*? for non-greedy regex

Upvotes: 1

Related Questions