Your challenge is to expand some brackets in a program's input as shown:
- Find a string s between two matching brackets
[
and]
, with a single digit n after the closing bracket. - Remove the brackets.
- Replace s with itself repeated n times. (If n is 0, simply remove s.)
- Go to step 1 until there are no more matching brackets in the input.
Additional rules and clarifications:
- You will take input and give output via any allowed means.
- A trailing newline in the output is allowed.
- You only need to handle printable ASCII in the input.
- You may assume that all brackets match, i.e. you will never receive the input
[]]]]
or[[[[]
. - You may assume that each closing bracket
]
has a digit after it.
Test cases:
Input -> Output
[Foo[Bar]3]2 -> FooBarBarBarFooBarBarBar
[one]1[two]2[three]3 -> onetwotwothreethreethree
[three[two[one]1]2]3 -> threetwoonetwoonethreetwoonetwoonethreetwoonetwoone
[!@#[$%^[&*(]2]2]2 -> !@#$%^&*(&*($%^&*(&*(!@#$%^&*(&*($%^&*(&*(
[[foo bar baz]1]1 -> foo bar baz
[only once]12 -> only once2
[only twice]23456789 -> only twiceonly twice3456789
[remove me!]0 ->
before [in ]2after -> before in in after
As this is code-golf, the shortest answer in each language wins. Good luck!
s
should never contain other brackets? For example, attempting to solve[Foo[Bar]3]2
by expanding the stringFoo[Bar
3 times would result in an invalid stateFoo[BarFoo[BarFoo[Bar]2
\$\endgroup\$[a[b]2c[d]2e]2
? You getabbcddeabbcdde
by expandingb
andd
first, butababcdbcdedbabcdbcdede
by expandinga[b
andd]2e
first. \$\endgroup\$