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
  • 3,453
  • 7
  • 31
  • 63

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
  • 412,405
  • 93
  • 575
  • 722
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
  • 44,416
  • 5
  • 53
  • 99
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,808
  • 5
  • 32
  • 49