How to split a string on whatever number of spaces, but also keep them all?

I have a string like “a b c d” (note the increasing number of spaces) and I would like to get it split as: [“a “, “b “, “c “, “d”].

I have seen the usage of look-behind, but it does not seem to work if the expected delimiter is potentially made of multiple characters, e..g, this does not work:

String[] parts = text.split(“(?<=([//s]+))”);

as it returns the extra white spaces after the first as separate matches, that is, it returns [“a “, “b “, ” “, “c “, ” “, ” “, “d”].

Is there a way to do it in a one liner, or do I have to merge back the extra spaces in post processing?

Instead of split use following for matching in a matcher.find() loop:


This regex matches one or more non-whitespace characters followed by zero or more whitespaces.

RegEx Demo


final String regex = "//S+//s*";
final String string = "a b  c   d";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

List<String> result = new ArrayList<>();

while (matcher.find()) {
    result.add( );