14

I have this text and I want to capture

begin
text 
end

begin
text 
end

begin
text 
end

the text between the begin and end.

/begin.*end/

this will capture the first begin and the last end.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
barak
  • 869
  • 1
  • 11
  • 15

2 Answers2

13

Make it lazy - /begin.*?end/

Sidenote: "lazy" is no less acceptable than "non-greedy" is. Example, example, example

Leonid
  • 3,121
  • 24
  • 31
4

If your text contains line feeds (\n or \r) you'll need to add the "dotall" flag to your regex, as well as make your match reluctant (ie "non greedy")

Depending on your regex flavour:

/begin.*?end/s
(?s)begin.*?end
Unihedron
  • 10,902
  • 13
  • 62
  • 72
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    js version; `/begin.*?end/s` [doesn't work in regex101 ](https://regex101.com/r/HzsPk7/1) while [python version](https://regex101.com/r/zsq4IQ/1) does. I tried whit scaped `\s` but no matches. – Mikel Nov 04 '16 at 12:31
  • @Mike of course `/begin.*?end/s` doesn't work in regex 101, because the forward slashes are not part of the regex. They are delimiters in js, but people frequently include them in js-related regex answers because that's how you code them (ie slashes instead of quotes, and flag after the regex also delimited by slashes). It's akin to coding the non js version with quotes in an answer, like `"(?s)begin.*?end"` (which people also sometimes do too). – Bohemian Nov 04 '16 at 13:11