Remove newline characters that appear between curly brackets
<p>I'm currently writing a text processing script which contains static text and variable values (surrounded by curly brackets). I need to be able to strip out newline characters but only if they appear between the curly brackets:</p>

<p><code>Some text\nwith a {variable\n} value"</code></p>

<p>to:</p>

<p><code>Some text\nwith a {variable} value"</code></p>

<p>Further down in the processing I'm already doing this:</p>

<p><code>re.sub(r'\{.*?\}', '(.*)', text, flags=re.MULTILINE|re.DOTALL)</code></p>

<p>But I'm not sure how to target just the newline character and not the entirely of the curly bracket pair. There is also the possibility of multiple newlines:</p>

<p><code>Some text\nwith a {variable\n\n\n} value"</code></p>

<hr>

<p>Using Python 3.x</p>

<p>You may pass the match object to a lambda in a <code>re.sub</code> and replace all newlines inside <code>{...}</code>:</p>

<pre><code>import re
text = 'Some text\nwith a {variable\n} value"'
print(re.sub(r'{.*?}', lambda m: m.group().replace("\n", ""), text, flags=re.DOTALL))
</code></pre>

<p>See <a href="http://ideone.com/ElV2ph" rel="nofollow">online Python 3 demo</a></p>

<p>Note that you do not need <code>re.MULTILINE</code> flag with this regex as it has no <code>^</code>/<code>$</code> anchors to redefine the behavior of, and you do not need to escape <code>{</code> and <code>}</code> in the current expression (without excessive backslashes, regexps look cleaner).</p>

python regex python-3.x