How to use regex to replace a particular field in a formatted file
<p>I have a file with following formatted file I need to parse</p>

<pre><code>field_1 {
    field_2 {
        ....
    }
    field_i_want_to_replace {
        ....
    }
    ....
}
....
</code></pre>

<p>I need a pre-processor in python to parse those files and delete the content of some particular fields. In the above example, the processed file will look like:</p>

<pre><code>field_1 {
    field_2 {
        ....
    }
    field_i_want_to_replace {}
    ....
}
....
</code></pre>

<p>So the preprocessor needs to locate the particular field "field_i_want_to_replace" and then delete the contents between the brackets. I'm trying to do the following but the regex can't parse the file correctly.</p>

<pre><code>regex = r'(field_i_want_to_replace )\{.*?\}'
print re.sub(regex,'field_i_want_to_replace {}', file_in_string)
</code></pre>

<p>Is there sth wrong with the regex I'm using?</p>

<p>Your <code>.</code> character is not matching any newlines, so it will not continue after the left curly bracket.</p>

<p>To change this behavior, just add the <a href="https://docs.python.org/2/library/re.html#re.DOTALL" rel="nofollow"><code>re.DOTALL</code> flag</a> (or <code>re.S</code>) as a keyword arg to your <code>re.sub</code>:</p>

<pre><code>&gt;&gt;&gt; regex = r'(field_i_want_to_replace )\{.*?\}'
&gt;&gt;&gt; print re.sub(regex,'field_i_want_to_replace {}', file_in_string, flags=re.DOTALL)
field_1 {
    field_2 {
        ....
    }
    field_i_want_to_replace {}
    ....
}
</code></pre>

python regex