This is sort of a follow-up to Python regex - Replace single quotes and brackets thread.
The task:
Sample input strings:
RSQ(nam
Please do not do this in any code I have to maintain.
You are trying to parse syntactically valid Python. Use ast for that. It's more readable, easier to extend to new syntax, and won't fall apart on some weird corner case.
Working sample:
from ast import parse
l = [
"RSQ(name['BAKD DK'], name['A DKJ'])",
"SMT(name['BAKD DK'], name['A DKJ'], name['S QRT'])"
]
for item in l:
tree = parse(item)
args = [arg.slice.value.s for arg in tree.body[0].value.args]
output = "XYZ({})".format(", ".join(args))
print(output)
Prints:
XYZ(BAKD DK, A DKJ)
XYZ(BAKD DK, A DKJ, S QRT)