2

How to split string to array where delimeter is also a token? For example, I have a string "var1 * var2 + var3" or "var1*var2+var3", and I want to split this string with delimeter "[\\+\\/\\+\\-]" such a way that the result will be a such array:

{"var1 ", "*", " var2 ", "+", " var3"} 

(or {"var1", "*", "var2", "+", "var3"})

How can I do this?

2
  • 1
    @Tim except spaces should be preserved according to sample output Commented May 26, 2016 at 10:28
  • Regarding the above comment, I had commented earlier that the OP might be able to simply split on space, which apparently is not the case. Commented May 26, 2016 at 11:33

3 Answers 3

2

Use a delimiter that doesn't consume. Say hello to look-behinds and look-aheads, which assert but do not consume:

String array = str.split("(?<=[*+/-])|(?=[*+/-])"); 

The regex matches either immediately after, or immediately before, math operators.

Note also how you don't need to escape the math operators when inside a character class.

Sign up to request clarification or add additional context in comments.

Comments

0

Practically, your delimiter should be the space or the blanks:

string.split("(\\b)+") 

This splits by blank spaces, so both the operators and variables end up in the resulting array.

1 Comment

Spaces should be preserved according to OP
0

Can't you just split by blank space?

String splittedString = string.split(" "); 

Also, same question here:

How to split a string, but also keep the delimiters?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.