How can I split these simple mathematical expressions into seperate strings?
I know that I basically want to use the regular expression: \"[0-9]+|[*+-^()]\"
This works for the sample string you posted:
String s = "578+223-5^2";
String[] tokens = s.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
The regex is made up entirely of lookaheads and lookbehinds; it matches a position (not a character, but a "gap" between characters), that is either preceded by a digit and followed by a non-digit, or preceded by a non-digit and followed by a digit.
Be aware that regexes are not well suited to the task of parsing math expressions. In particular, regexes can't easily handle balanced delimiters like parentheses, especially if they can be nested. (Some regex flavors have extensions which make that sort of thing easier, but not Java's.)
Beyond this point, you'll want to process the string using more mundane methods like charAt()
and substring()
and Integer.parseInt()
. Or, if this isn't a learning exercise, use an existing math expression parsing library.
EDIT: ...or eval()
it as @Syzygy recommends.