java - How to extract operators from specific portion of a linear expression using regex -


i have linear expression have extract operators specific places.i dont need extract operators.i.e expression

c*(a+b)+(a-b)/log(a+b)-(b-c/d)+(d-tan90) 

the operators inside bracket dont need separated. operators in between 2 elements separated.i.e desired output

*,+,/,-,+ can help?

if need operators, think expression parser overkill.

it's simple loop through characters , store off operators. (minor) complexity keeping track of count of parentheses.

this snippet give output desired, , work if end nested expressions:

    string expression = "c*(a+b)+(a-b)/log(a+b)-(b-c/d)+(d-tan90)";     list<character> operators = new arraylist<character>();     int parentheses = 0;     (char c : expression.tochararray()) {         // throw away inside ( )         if (c == '(') {             parentheses++;         } else if (c == ')') {             parentheses--;         }         if (parentheses > 0) {             continue;         }          // store operators outside ( )         if (c == '+' || c == '-' || c == '*' || c == '/') {             operators.add(c);         }     }     system.out.println(operators);  // [*, +, /, -, +] 

note i'm assuming you're working on valid mathematical expression here. if aren't sure you're going input, you'd need validate it.

if you're planning on doing fancier, might want use expression parser (such jep or formula4j).


Comments

Popular posts from this blog

Python Kivy ListView: How to delete selected ListItemButton? -

asp.net mvc 4 - A specified Include path is not valid. The EntityType '' does not declare a navigation property with the name '' -