Retrieve text within multiple brackets in python

Viewed 64

Suppose I have a string like this:

str = 'Concat(((("function_test"."PRODUCT_CATEGORIES"."CATEGORY_NAME" ), ("function_test"."PRODUCT_CATEGORIES"."CATEGORY_NAME" )) ))'

I get the contents within concat function as

((("function_test"."PRODUCT_CATEGORIES"."CATEGORY_NAME" ), ("function_test"."PRODUCT_CATEGORIES"."CATEGORY_NAME" )) )

Now I want to remove the round brackets present in str and output should be

"function_test"."PRODUCT_CATEGORIES"."CATEGORY_NAME" , "function_test"."PRODUCT_CATEGORIES"."CATEGORY_NAME" 

This is what I have tried:

res= str.strip().replace('(','').replace(')','')

Is there any better approach I can follow to get the required output. Please help

1 Answers

This is a job for regular expressions!

Mine is ugly but it works:

import re

# I changed this a bit for testing, but the spirit is the same.
s = '''((("function_test"."PRODUCT_CATEGORIES"."CATEGORY_NAME" ), ("function_test"."PRODUCT_CATEGORIES"."something else" )) )'''
pat = r'\(([^\(\)]+)\)'
s_list = re.findall(pat, s)

Which returns:

 ['"function_test"."PRODUCT_CATEGORIES"."CATEGORY_NAME" ','"function_test"."PRODUCT_CATEGORIES"."something else" ']

If you want a string instead of a list, you can add:

 ','.join(s_list)
Related