Python regex - Replace bracketed text with contents of brackets
<p>I'm trying to write a Python function that replaces instances of text surrounded with curly braces with the contents of the braces, while leaving empty brace-pairs alone. For example: </p>

<p><code>foo {} bar {baz}</code> would become <code>foo {} bar baz</code>. </p>

<p>The pattern that I've created to match this is <code>{[^{}]+}</code>, i.e. some text that doesn't contain curly braces (to prevent overlapping matches) surrounded by a set of curly braces.</p>

<p>The obvious solution is to use <code>re.sub</code> with my pattern, and I've found that I can reference the matched text with <code>\g&lt;0&gt;</code>:</p>

<pre><code>&gt;&gt;&gt; re.sub("{[^{}]+}", "A \g&lt;0&gt; B", "foo {} bar {baz}")
'foo {} bar A {baz} B'
</code></pre>

<p>So that's no problem. However, I'm stuck on how to trim the brackets from the referenced text. If I try applying a range to the replacement string:</p>

<pre><code>&gt;&gt;&gt; re.sub("{[^{}]+}", "\g&lt;0&gt;"[1:-1], "foo{}bar{baz}")
'foo{}barg&lt;0'
</code></pre>

<p>The range is applied before the <code>\g&lt;0&gt;</code> is resolved to the matched text, and it trims the leading <code>\</code> and trailing <code>&gt;</code>, leaving just <code>g&lt;0</code>, which has no special meaning. </p>

<p>I also tried defining a function to perform the trimming:</p>

<pre><code>def trimBraces(string):
    return string[1:-1]
</code></pre>

<p>But, unsurprisingly, that didn't change anything.</p>

<pre><code>&gt;&gt;&gt; re.sub("{[^{}]+}", trimBraces("\g&lt;0&gt;"), "foo{}bar{baz}")
'foo{}barg&lt;0'
</code></pre>

<p>What am I missing here? Many thanks in advance.</p>