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.

0

2 Answers 2

13

Make it lazy - /begin.*?end/

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

1
  • 7
    The term is "non greedy" (not "lazy")
    – Bohemian
    Sep 9, 2011 at 11:21
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
2
  • 1
    js version; /begin.*?end/s [doesn't work in regex101 ](regex101.com/r/HzsPk7/1) while python version does. I tried whit scaped \s but no matches.
    – Mikel
    Nov 4, 2016 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 4, 2016 at 13:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.