-1

i used this code to split the mathematical expression. how can i save the number in String named Value 1/2/3 and operators in String named operator 1/2?

enter code here

String myString= "1+2/3";
String[] result = myString.split("(?<=[-+*/])|(?=[-+*/])");
System.out.println(Arrays.toString(result));
Rick Bronger
  • 330
  • 1
  • 15
John Smith
  • 19
  • 5

2 Answers2

1

Just because I cannot comment I'm writing down as an answer. The answer @Chirag Parmar seems correct, however it does not work, if there are decimal numbers in the string.

So, switch "\\d" with "\\d+(\\.\\d{1,2})?" and it works.

0

EDIT: Thanks everyone for pointing me out. Special thanks to @Çağatay Karslı

    String myString= "1+2/3";
    String[] results = myString.split("(?<=[-+*/])|(?=[-+*/])");
    List<String> values = new ArrayList<>();
    List<String> operators = new ArrayList<>();
    for(String result :results) {
        if(result.matches("\\d+(\\.\\d{1,2})?")) { //corrected
            values.add(result);
        }else {
            operators.add(result);
        }
    }
    System.out.println(values);     //[1, 2, 3]
    System.out.println(operators);  //[+, /]
Chirag Parmar
  • 833
  • 11
  • 26