The following:
String q ="(ADD(EXP 1 4)(SQR 1)(DIV 34 77)(MULT 12 5 3 7)(Sub 1 2";
String[] result = q.split("(?=\\()");
produces the following strings in the result array:
"(ADD"
"(EXP 1 4)"
"(SQR 1)"
"(DIV 34 77)"
"(MULT 12 5 3 7)"
"(Sub 1 2"
but I'm not totally sure that's what you want (if it isn't, you'll need to clarify for us).
The argument to split
is a regular expression. It's common to use it with something like "/"
, which will split an input string by slash characters. But doing that doesn't leave the slash characters in the result. To split
on a string but leave the delimiters in the results, you need lookahead. The regular expression above does that. (?=<something>)
looks ahead for some pattern but doesn't "consume" it; here the pattern is \\(
which means a single (
character, but it needs to be preceded by a backslash because (
normally has special meanings in a regular expression.