orangespire orangespire - 12 days ago 5
Java Question

Splitting a string keeping some delimiters but removing another

Basically I would like to split a string into an array delimiting by spaces and operators, but keep the operators while removing the spaces

ex.

3 52 9+- 2 3 * /


will be
[3][52][9][+][-][2][3][*][/]

Answer

The logic you want when splitting is to consume delimiters which are whitespace and to not consume delimiters which are arithmetic symbols. Towards this end, we can use a lookahead to split by symbol, and use plain \\s to split by whitespace and remove it from the result.

String input = "3 52 9+- 2 3 * /";
input = input.replaceAll("([\\+\\-*/])(.)", " $1$2")
             .replaceAll("\\s+", " ");

String[] parts = input.split("(?<=[\+\-*/])|\\s")

System.out.println(Arrays.toString(parts));

Output:

[3, 52, 9, +,  -,  2, 3, *,  /]
Comments