Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 ?

share|improve this question
 
 
Just a comment. For all that complex regex you have within your double quotes, you could've just had a "//D", –  Vijairam Sep 11 '13 at 22:21
add comment

2 Answers

up vote 5 down vote accepted

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.

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.