2

for example: strEquation="36+5-8X2/2.5"

My code is :

String[] tmp = strEquation.split("[X\\+\\-\\/]+");

for(int i=0; i<tmp.length; i++)
    Log.d("Split array",tmp[i]);

and my output as i thought it would be :

36
5
8
2
2.5

I want the tmp string array will put also the char I'm splitting with, like this:

tmp[0] = 36
tmp[1] = +
tmp[2] = 5
tmp[3] = -
tmp[4] = 8
tmp[5] = X
tmp[6] = 2
tmp[7] = /
tmp[8] = 2.5

Any idea how to do that ?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
SilverCrow
  • 167
  • 1
  • 12
  • check these links http://stackoverflow.com/questions/275768/is-there-a-way-to-split-strings-with-string-split-and-include-the-delimiters and http://stackoverflow.com/questions/2206378/how-to-split-a-string-but-also-keep-the-delimiters – Ranjith Sep 11 '13 at 21:50
  • Just a comment. For all that complex regex you have within your double quotes, you could've just had a "//D", – VictorCreator Sep 11 '13 at 22:21

2 Answers2

7

How about splitting before or after each of X + - / characters? BTW you don't have to escape + and / in character class ([...])

String[] tmp = strEquation.split("(?=[X+\\-/])|(?<=[X+\\-/])");

seems to do the trick.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

I would say that you're trying to get all the matches and not to split the string so

Matcher m = Pattern.compile("[X+/-]|[^X+/-]+").matcher(strEquation);
while (m.find()) {
  System.out.println(m.group());
}

but the answer above is more clever :)

Also: you don't need to escape + and / chars inside of square braces; minus (-) sign need to be escaped only if it's not first or last character on the list

Adassko
  • 5,201
  • 20
  • 37