java – String.split() to split on spaces, but without replacing spaces

Question:

I have a String like the following:

String foo = "soy un texto" 

By applying the following function:

String []  bar = foo. split(" ");

He separates it into three texts:

"soy", "un" y "texto" 

However, I want it to keep the spaces like the following example:

"soy",  " un"  y " texto" 

How can I do that?

Answer:

With the specs cleared up the regex you can use in split is:

String foo = "Soy un texto";
String[] bar = foo.split("(?=\\s)");
for (String foobar : bar ){
    System.out.println(String.format("<%s>", foobar));
}

(?=X) makes you a match of places followed by a space, without consuming characters.

Result:

<Soy>
< un>
< texto> 
Scroll to Top