I am going to answer the first question. I could not complete the task in one replaceAll . I do not think this is even possible. However, if I use a loop, this should do the job for you:
String termString = "([0-9+\\-*/()%]*)"; String pattern = "ABC\\(" + termString + "\\," + termString + "\\)"; String [] strings = {"ABC(10,5)", "ABC(ABC(20,2),5)", "ABC(ABC(30,2),3+2)"}; for (String str : strings) { while (true) { String replaced = str.replaceAll(pattern, "($1)%($2)"); if (replaced.equals(str)) { break; } str = replaced; } System.out.println(str); }
I assume that you are writing a parser for numeric expressions, thus defining the term termString = "([0-9+\\-*/()%]*)" . He outputs this:
(10)%(5) ((20)%(2))%(5) ((30)%(2))%(3+2)
EDIT . As per the OP request, I add code to decode the strings. This is a bit more hacky than the direct scenario:
String [] encoded = {"(10)%(5)", "((20)%(2))%(5)", "((30)%(2))%(3+2)"}; String decodeTerm = "([0-9+\\-*ABC\\[\\],]*)"; String decodePattern = "\\(" + decodeTerm + "\\)%\\(" + decodeTerm + "\\)"; for (String str : encoded) { while (true) { String replaced = str.replaceAll(decodePattern, "ABC[$1,$2]"); if (replaced.equals(str)) { break; } str = replaced; } str = str.replaceAll("\\[", "("); str = str.replaceAll("\\]", ")"); System.out.println(str); }
And the result:
ABC(10,5) ABC(ABC(20,2),5) ABC(ABC(30,2),3+2)