ERohan ERohan - 5 months ago 17
Java Question

Java String.split() - splitting a string using //s+ doesn't capture parentheses as separate elements?

Let's say I have a string: "(2 * 32) + 5 ^ 2"

I'd like to turn this into a String array: [(, 2, *, 32, ), +, 5, ^, 2]

i.e. I don't want to capture spaces in the original string and I want to split by whitespace characters.

So I tried string.split**("\\s+")** but the result looks like [(2,*,32), +, 5, ^, 2].

Can someone explain why it doesn't split "(2" into (,2? Thank you!

Answer

This works, and has the added benefit of not splitting when there are numbers longer than 1 digit:

String str = "(2*32) + 5 ^ 2";
String[] tokens = str.replace(" ", "").split("\\b|(?=\\D)");

Output:

[ (, 2, *, 32, ), +, 5, ^, 2 ]

Ideone Demo