I need to parse an expression such as: neg(and(X,Y))
I need it to come out with the Abstract Stack Machine Code Such as for the example above:
LOAD X;
LOAD Y;
EXEC and;
EXEC neg;
But for now the machine code is not an issue, how can i parse / break up my input string of an expression into all its sub expressions?
I have tried to find the first bracket and then concat from that to the last bracket but that then gives isuess if you have a inner expression?
code that i have tried: (please not it is still very much in the development phase)
private boolean evaluateExpression(String expression) {
int brackets = 0;
int beginIndex = -1;
int endIndex = -1;
for (int i = 0; i < expression.length(); i++) {
if (expression.charAt(i) == '(') {
brackets++;
if (brackets == 0) {
endIndex = i;
System.out.println("the first expression ends at " + i);
}
}
if (expression.charAt(i) == ')') {
brackets--;
if (brackets == 0) {
endIndex = i;
System.out.println("the first expression ends at " + i);
}
}
}
// Check for 1st bracket
for (int i = 0; i < expression.length(); i++) {
if (expression.charAt(i) == '(') {
beginIndex = i;
break;
}
}
String subExpression = expression.substring(beginIndex, endIndex);
System.out.println("Sub expression: " + subExpression);
evaluateExpression(subExpression);
return false;
}
I am just looking for a basic solution, It only has to do: and, or, neg
Actually if you want your parser to be strong enough to deal with most cases, you would like to use a tokenizer(java has a implemented tokenizer class) to token the string first, then try to recognize each expression, storing operands and operators in a tree structure, then evaluate them recursively.
If you only want to deal with some simple situations, remember to use recursion, that is the core part~