Basically what I am trying to accomplish is whenever a number precedes a string within square brackets, the string within the square brackets should repeat as many times. I am learning regular expression and I posted a question how I can come up with a regular expression for this scenario and folks were kind enough to get me what I wanted. Basically the code below parses the string based on the regular expression and get me a list with all square brackets removed so that I can iterate through the list and get myself the output I want.
Given a string s, the code I have is below. But this does not work in all scenarios. This however works when there are no nested square brackets.
import re
s = "abc3[cd]xyz"
s_final = ""
res = re.findall(r'\d+|[^\W\d_]+', s)
print(res)
for i in range(len(res)):
if res[i].isnumeric():
s_final+=int(res[i])*res[i+1]
else:
if res[i] not in s_final:
s_final += res[i]
print(s_final)
if I change the string to
s = "3[a2[c]]" the expected output is accaccacc as the inner square brackets gets evaluated first and then the outer square brackets. But what I get is aaacc which is not wrong based on the code I have. But anyone have any insights on how I can evaluate the string correctly?
Thanks!