How to split a string to get the last item in braces?
<p>I'm trying to split a string to extract the last item in braces.</p>

<p>For example if I had the string</p>

<pre><code>'Stud Rd/(after) Ferntree Gully Rd (Scoresby)'
</code></pre>

<p>I would like to split it into the components</p>

<pre><code>('Stud Rd/(after) Ferntree Gully Rd', 'Scoresby')
</code></pre>

<p>So far I've written the following regex to do this</p>

<pre><code>re.search(r'^(.*) \((.*)\)$', string)
</code></pre>

<p>However this breaks in the case of an input like</p>

<pre><code>'Bell St/Oriel Rd (Bellfield (3081))'
</code></pre>

<p>Which I would like be split into</p>

<pre><code>('Bell St/Oriel Rd', 'Bellfield (3081)')
</code></pre>

<p>Is there a better way then this to approach this problem?</p>

<p>Change your regex pattern and work with <strong>match</strong> object(returned by <code>search</code> function) in proper way:</p>

<pre><code>import re

str = 'Bell St/Oriel Rd (Bellfield (3081))'
result = re.search(r'^(.*?) \((.*?)\)$', str)

print(result.group(1,2))   # ('Bell St/Oriel Rd', 'Bellfield (3081)')
</code></pre>

python regex