Regex match exact amount of character on multi line string

Question:

I have a text something like below.

    start
        foo1
        bar1
    stop

        start
            foo2
            bar2
        stop

    start
       oof
       rab
    stop

I need to capture text between start and stop but only starting with only four white spaces. So I want to capture first and third part of the text. Can you help please?

I wrote something like this. dotall is active (dot matches new line)

r's{4}start.*?s{4}stop'

But it doesn’t work. It still captures all blocks. ^ doesn’t work since all text is behaving a single line.

Asked By: MuratT

||

Answers:

Set the regex flags this way:

  1. Use single line flag (re.S) so the . matches newlines;
  2. Use re.M so that the ^ anchor matches with multiple lines.

Then:

r'^s{4}startb.*?^s{4}stopb'

works

Demo

Python Demo

Answered By: dawg
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.