0

I have a linear expression which I have to use for some calculation purpose. But I can not manage to use it properly by separating on the basis of operators. i.e I have an expression

"c*(a+b)+(a-b)"

from which I have to extract c,(a+b),(a-b) .I am able to separate c from there but I can not separate (a+b) and (a-b) .I am doing this

                String linearExp="c*(a+b)+(a-b)";
    String leftOperators=null;
    String rightOperators=null;

    for(int i=0;i<linearExp.length();i++){

        leftOperators=linearExp.substring(0,linearExp.lastIndexOf("*"));
        rightOperators=linearExp.substring(linearExp.lastIndexOf("*")+1);
    }
    System.out.println(leftOperators);
    System.out.println(rightOperators);  

This is doing output like c & (a+b)+(a-b).But I a need (a+b) &(a-b) separate also.somebody please help

Subho
  • 921
  • 5
  • 25
  • 48
  • 2
    provide some more inputs to make it more clear. – Braj Sep 20 '14 at 16:28
  • I'm no expert on this, but it would seem to me that you would need some sort of stack or stacks to push variables and operators in on and to allow nesting of parenthesis if it occurs. – Hovercraft Full Of Eels Sep 20 '14 at 16:29
  • @subho there is a simple solution also for that.you can use the built-in Javascript engine .take a look http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – Madhawa Priyashantha Sep 20 '14 at 16:37
  • The above code separate left side and right side of star character.. You need to separate based on the parenthesis... Use stack and start adding characters then if your encounter ( then pop everything from stack when u encounter ) pop till you get (... Try this.. – praveen_mohan Sep 20 '14 at 16:37
  • can anyone provide regex to extract the operators also? – Subho Sep 20 '14 at 18:11

1 Answers1

0

This is solely based off your given expression and will not work for nested parenthesis.

One way using regex implementing lookarounds to split on the operators.

String s = "c*(a+b)+(a-b)";
String[] parts = s.split("(?<=\\))[*+/-]|[*+/-](?=\\()");
System.out.println(Arrays.toString(parts)); //=> [c, (a+b), (a-b)]
hwnd
  • 69,796
  • 4
  • 95
  • 132