Simon Gibbons Simon Gibbons - 6 months ago 23
Python Question

How to split a string to get the last item in braces?

I'm trying to split a string to extract the last item in braces.

For example if I had the string

'Stud Rd/(after) Ferntree Gully Rd (Scoresby)'

I would like to split it into the components

('Stud Rd/(after) Ferntree Gully Rd', 'Scoresby')

So far I've written the following regex to do this'^(.*) \((.*)\)$', string)

However this breaks in the case of an input like

'Bell St/Oriel Rd (Bellfield (3081))'

Which I would like be split into

('Bell St/Oriel Rd', 'Bellfield (3081)')

Is there a better way then this to approach this problem?


You can use this lazy regex:

(.*?) \((.*)\)[^()]*$

RegEx Demo


>>> reg = r'(.*?) \((.*)\)[^()]*$'

>>> s = 'Bell St/Oriel Rd (Bellfield (3081))'
>>> re.findall(reg, s)
[('Bell St/Oriel Rd', 'Bellfield (3081)')]

>>> s = 'Stud Rd/(after) Ferntree Gully Rd (Scoresby)'
>>> re.findall(reg, s)
[('Stud Rd/(after) Ferntree Gully Rd', 'Scoresby')]