How to Split a mathematical expression on operators as delimiters, while keeping them in the result?

前端 未结 5 1051
忘了有多久
忘了有多久 2020-11-29 09:36

I need to split an expression like

a+b-c*d/e 

and get a, b, c, d, e sepe

5条回答
  •  囚心锁ツ
    2020-11-29 10:36

    Just to get the a/b/c/d/e:

    String myString = "a+b-c*d/e";
    String[] result=myString.split("[-+*/]");
    

    In a more readable form:

    String myString = "a+b-c*d/e";
    String[] result2=myString.split("["+Pattern.quote("+-*/")+"]");
    

    To get the +-*/:

    ArrayList list = new ArrayList();
    for (char c:myString.toCharArray())
    {
       if ("+-*/".contains(""+c)) list.add(c);
    }
    System.out.println(list);
    

    Edit: removed unneeded escape characters.

提交回复
热议问题