Is there any way to split the string in the way I want using regex?
No, there is not. A regex (if it matches) returns the string and sub-strings that you surround by ()
, or a list of all complete matches if you use the global flag. You don't get a nested list of items that are the children of other matches.
Combining this with just Java would do the trick. I don't know Java, but I'll try to explain with this java-like code:
Array match_children (Array input) {
Array output;
foreach (match in input) {
// The most important part!
// The string starts with "[", so it is the beginning of a new nest
if (match.startsWith("[")) {
// Use the same ragex as below
Array parents = string.match(matches 'dotimes' and all between '[' and ']');
// Now, call this same function again with the
match = match_children(parents);
// This stores an array in `match`
}
// Store match in output list
output.push(match);
}
return output;
}
String string = "dotimes [sum 1 2] [dotimes [sum 1 2] [sum 1 3]]";
// "dotimes [sum 1 2] [dotimes [sum 1 2] [sum 1 3]]"
Array parents = string.match(matches 'dotimes' and all between '[' and ']');
// "dotimes", "[sum 1 2]", "[dotimes [sum 1 2] [sum 1 3]]"
// Make sure to use a global flag
Array result = match_children(Array input);
// dotimes
// [
// sum 1 2
// ]
// [
// dotimes
// [
// sum 1 2
// ]
// [
// sum 1 3
// ]
// ]
Again, I don't know Java and if it needs more clearification, just comment. :)
Hope this helps.