Another way to do it would be to apply a regex repeatedly to the string, a regex which looks for a balanced-parentheses group. Note the substring-position where that pattern begins, and calculate where it ends. Iterate through the loop, extracting the appropriate substrings given their now-known starting and ending positions. Source-code to do it left as an exercise for the reader.