java - Parse an Expression to its components and sub components -


i need parse expression such as: neg(and(x,y))

i need come out abstract stack machine code such example above:

load x; load y; exec and; exec neg; 

but machine code not issue, how can parse / break input string of expression sub expressions?

i have tried find first bracket , concat last bracket gives isuess if have inner expression?

code have tried: (please not still in development phase)

private boolean evaluateexpression(string expression) {      int brackets = 0;     int beginindex = -1;     int endindex = -1;      (int = 0; < expression.length(); i++) {         if (expression.charat(i) == '(') {             brackets++;              if (brackets == 0) {                 endindex = i;                 system.out.println("the first expression ends @ " + i);             }         }         if (expression.charat(i) == ')') {             brackets--;              if (brackets == 0) {                 endindex = i;                 system.out.println("the first expression ends @ " + i);             }         }     }     // check 1st bracket     (int = 0; < 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 looking basic solution, has do: and, or, neg

the expressions trying parse making context free language, can represented context free grammer.

you can create context free grammer represents language of expressions, , use cfg parser parse it.

one existing java tool (and more) javacc, though overkill here.
another algorithm parse sentences using cfg cyk, easy program , use.


in here, cfg representing available expressions are:

s -> or(s,s) s -> and(s,s) s -> not(s) s -> x | each variable x 

note though relatively simple cfg - language describes irregular, if hoping regex - it's not way go.


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -