Python - How to find and remove the first and last closing bracket of a string that consists of many sets of brackets in between

Viewed 60

I am trying to find all strings that begin with a specific word followed by an opening bracket up until the very last closing bracket of the string in a python code.I then want to remove that set of brackets. The problem is that the string contains many sets of brackets in-between so my code is detecting the first closing bracket instead of the very last closing bracket. I have used regex to solve the problem using the following function:

func_list = re.findall(rf"{word}\'\(.*?\)'", code)

The code manages to find the string and remove the brackets, however it detects the first opening bracket of the string and the first closing bracket instead of the last closing bracket

Initial String:

round(sum(CASE WHEN comparison_year = 'date_1' then cast(QTY as float)  end)) 

Output:

round sum(CASE WHEN comparison_year = 'date_1' then cast(QTY as float  end)) 

Desired Output:

round sum(CASE WHEN comparison_year = 'date_1' then cast(QTY as float) end)

Assistance will be much appreciated

1 Answers

try this:

text = "round(sum(CASE WHEN comparison_year = 'date_1' then cast(QTY as float) end))"
print(text.replace('(', '', 1).rsplit(')', 1)[0])

>>> roundsum(CASE WHEN comparison_year = 'date_1' then cast(QTY as float) end)
Related