1

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
Community
  • 1
  • 1
Saif
  • 6,804
  • 8
  • 40
  • 61

1 Answers1

1

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • that's seems right. one last think, can you please confirm that it will work in java Pattern and Matcher .? – Saif Feb 16 '15 at 06:33
  • Yes it will definitely work in Java. Just make sure to use `DOTALL` flag in Java using `Pattern.DOTALL` (2nd parameter in `Pattern.compile` call) – anubhava Feb 16 '15 at 06:36