Java Separate string by spaces not surrounded by [ ] brackets

java, regex

Solution

Does it have to be regex? You can do it in one iteration just by counting how many brackets ware before space to determine if that space should be replaced by new line mark or not.

String data="book [new [interesting] book] buy it";
StringBuilder buffer=new StringBuilder();
int bracketCounter=0;
for (char c:data.toCharArray()){
    if (c=='[') bracketCounter++;
    if (c==']') bracketCounter--;
    if (c==' ' && bracketCounter==0)
        buffer.append("\n");
    else 
        buffer.append(c);
}
System.out.println(buffer);

Out:

book
[new [interesting] book]
buy
it

Problem

How do I split a string by whitespaces if it is not surrounded with this kind of bracket [ ] So the string `" book [new interesting book] buy it "` should be split in ``` book new interesting book buy it ``` or ``` book [new interesting book] buy it ``` Thank you!

Original source