-1
String s = " x  +  y  ";
String[] sArr = s.split("\\s*-|+|*|/\\s*"); 

I have a String such as: " x + y " I want to get an array with elements: x, +, y (no whitespaces) Instead of +, if I use -,/,* they should also work. I was trying something like the above code, but this gives errors because of + and/or *. It takes them as part of the regular expression.

How can I make this work? Please help.

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
  • 1
    Have you tried just splitting on white spaces? `s.split("\\s*")`. The argument to split tells you what should come _between_ the elements you want to keep. Since you want to keep the `+`, it shouldn't be part of the `split` regex unless you're doing something really tricky. – ajb Mar 06 '17 at 05:01
  • `s.replaceAll("\\s","").split("")` – Niraj Chauhan Mar 06 '17 at 05:02

2 Answers2

1
String s = " x  +  y  ";
String[] sArr = s.trim().split("\\s+"); 
System.out.println(sArr[0]+":"+sArr[1]+":"+sArr[2]);

Output: x:+:y

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
  • you code will not work if input string doesn't contain space in between. – Wasi Ahmad Mar 06 '17 at 05:56
  • There should be some separator to separate one word from another. In this question OP is clearly asking to to separate by space. Otherwise how do you separate a String like " x + 25 + 50 " if you don't know what is the separator ? – Sisir Ranjan Mar 06 '17 at 07:00
  • yes, OP probably wants to separate the string using the operator sign. – Wasi Ahmad Mar 06 '17 at 07:16
1
String s = " x  +  y - z / x * y ";
s = s.replaceAll("\\s+", "");

1st alternative:

String[] sArr = s.split("((?<=[\\+\\-\\*/])|(?=[\\+\\-\\*/]))");
System.out.println(Arrays.toString(sArr));

Reference: https://stackoverflow.com/a/2206432/5352399

2nd alternative:

String[] sArr = s.split("\\s*");
System.out.println(Arrays.toString(sArr));

In both cases, output:

[x, +, y, -, z, /, x, *, y]

If you don't want the operators in the output, you can do something like this.

String[] sArr = s.split("\\s*[-,+,*,/]\\s*");
System.out.println(Arrays.toString(sArr));

Output:

[x, y, z, x, y]
Community
  • 1
  • 1
Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161