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>Assuming you have un-nested, balanced brackets you can use this lookahead regex to replace newline between <code>{...}</code>:</p>

<pre><code>&gt;&gt;&gt; s = "Some text\nwith a {variable\n} value"
&gt;&gt;&gt; print re.sub(r'\n(?=[^{}]*})', '', s)
Some text
with a {variable} value
</code></pre>

<p><code>(?=[^{}]*})</code> is lookahead to assert we have a closing <code>}</code> ahead of newline without matching a <code>{</code> or <code>}</code> before closing <code>}</code>.</p>

python regex python-3.x