1

I am trying to split a string into tokens based on regex. However the split() gives error saying Illegal Escape Sequencce.

I'm trying to split the following string into tokens.

For example the following string convert into

1+2.0-3.145/4.0

this

1 2.0 3.145 4.0

& this

+ - /

This is the regex I have written but this has some issues and gives error.

String[] tokens = expression.split("\\+\\-\\x\\/");

What am I doing wrong?

EDIT: My end goal is to evaluate a string contaning mathematical expressions & calcualte its results. Is there any library that can be used on Android?

user2498079
  • 2,872
  • 8
  • 32
  • 60
  • 1
    Do you want to call `split` once with a `regex` to get two arrays? – shizhz Mar 25 '17 at 14:09
  • It will help you http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form or this http://stackoverflow.com/questions/1432245/how-to-parse-a-mathematical-expression-given-as-a-string-and-return-a-number – Roma Khomyshyn Mar 25 '17 at 14:18

2 Answers2

0

Update your regex to expression.split("[-+/]")

If you want to array you can use it:

 List<String> operators = new ArrayList<>();
 List<String> operands = new ArrayList<>();
 StringTokenizer st = new StringTokenizer(expression, "+-/", true);
 while (st.hasMoreTokens()) {
    String token = st.nextToken();

    if ("+-/".contains(token)) {
       operators.add(token);
    } else {
       operands.add(token);
    }
 }
Roma Khomyshyn
  • 1,112
  • 6
  • 9
  • But it won't return the special characters in a separate array in the exact order these special characters are present in the string – user2498079 Mar 25 '17 at 14:04
  • If you want special characters in separate array you have to slip source string to times. Or you can use this regex `(?<=[-+/])|(?=[-+/])` result will be (1, +, 2.0, -, 3.145, /, 4.0) – Roma Khomyshyn Mar 25 '17 at 14:10
0

It's very tricky evaluating an expression, like in which order they should be calculated luckily this has been solved before: http://www.geeksforgeeks.org/expression-evaluation/

And

@Roma Khomyshyn links are useful as well.

Chester Cobus
  • 701
  • 4
  • 12