How can I split a boolean expression in Java? For example, I want to get the following from the expression a_1 & b_2 | (!c_3):
String tokens[] = {"a_1", "&", "b_2", "|", "(", "!", "c_3", ")"};
The names of the variables contain alphanumeric characters and underscores (_).
If you want to parse the String - maybe to create a syntax tree and evaluate the expression -, then it's better to parse the String with a simple switch expression:
// for each char c in String
switch (c) {
case '&': processAnd();break;
case '|': processOr();break;
case '!': processNot();break;
case '(': processOpenPara();break;
case ')': processClosePara();break;
case ' ': break;
default: processVarName(); break;
}
This is just a stub to show the pattern. You may want to use a stack to evaluate the expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With