See this code:
String input = "((90+1)%(100-4)) + ((90+1)%(100-4/(6-4))) - (var1%(var2%var3(var4-var5)))"; input = input.replaceAll("%", ","); int level = 0; List<Integer> targetStack = new ArrayList<Integer>(); List<Integer> splitIndices = new ArrayList<Integer>(); // add the index of last character as default checkpoint splitIndices.add(input.length()); for (int i = input.length() - 1; i >= 0; i--) { if (input.charAt(i) == ',') { targetStack.add(level - 1); } else if (input.charAt(i) == ')') { level++; } else if (input.charAt(i) == '(') { level--; if (!targetStack.isEmpty() && level == targetStack.get(targetStack.size() - 1)) { splitIndices.add(i); } } } Collections.reverse(splitIndices); // reversing the indices so that they are in increasing order StringBuilder result = new StringBuilder(); for (int i = 1; i < splitIndices.size(); i++) { result.append("XYZ"); result.append(input.substring(splitIndices.get(i - 1), splitIndices.get(i))); } System.out.println(result);
The output is done as you expect:
XYZ((90+1),(100-4)) + XYZ((90+1),(100-4/(6-4))) - XYZ(var1,XYZ(var2,var3(var4-var5)))
However, keep in mind that it is a bit hacked and may not work as you expect. By the way, I had to change the result a bit: I added a couple of brackets: XYZ ((90 + 1), ( 100-4 / (6-4 ) )) because otherwise you will not follow your own conventions. Hope this code helps you. For me it was a good exercise, at least.
source share