How to use REGEX with multiline
<p>The following expression works well extracting the portion of <code>data</code> string that starts with the word <code>Block</code> followed by open bracket <code>{</code> and ending with the closing bracket '}':</p>

<pre><code>data ="""
Somewhere over the rainbow
Way up high 
Block {
 line 1
 line 2
 line 3
}
And the dreams that you dreamed of
Once in a lullaby
"""
regex = re.compile("""(Block\ {\n\ [^\{\}]*\n}\n)""", re.MULTILINE)
result = regex.findall(data)
print result 
</code></pre>

<p>which returns:</p>

<pre><code>['Block {\n line 1\n line 2\n line 3\n}\n']
</code></pre>

<p>But if there is another curly bracket inside of the Block portion of the string the expression breaks returning an empty list:</p>

<pre><code>data ="""
Somewhere over the rainbow
Way up high 
Block {
 line 1
 line 2
 {{}
 line 3
}
And the dreams that you dreamed of
Once in a lullaby
Block {
 line 4
 line 5
 {{
 }
 line 6
}
Somewhere over the rainbow
Blue birds fly
And the dreams that you dreamed of
Dreams really do come true ooh oh
"""
</code></pre>

<p>How to modify this regex expression to make it ignore the brackets that are inside of the Blocks and yet each block is returned as the separate entity in <code>result</code> list (so each Block could be accessed separately)?</p>

<p>Wouldn't this work?</p>

<p><code>regex = re.compile("""(Block\ {\n\ [^\}]*\n}\n)""", re.MULTILINE)</code></p>

<p>In the version you've posted, it is exiting the match whenever it comes across a second opening brace, even though you want it to exit upon the first closing brace.  If you want nested opening / closing braces that's another story.</p>

python regex