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?

Ksenia
  • 2,919
  • 7
  • 26
  • 55

3 Answers3

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.

Bohemian
  • 389,931
  • 88
  • 552
  • 692
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.

ernest_k
  • 42,928
  • 5
  • 50
  • 93
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?

Community
  • 1
  • 1
SCouto
  • 7,371
  • 4
  • 33
  • 47