If it doesn't have to be regex then you can use this simple parser and get your result in one iteration.
public static List<String> spaceSplit(String str) {
List<String> tokens = new ArrayList<>();
StringBuilder sb = new StringBuilder();
boolean insideEscaped = false; //flag to check if I can split on space
for (char ch : str.toCharArray()) {
if (ch == '\\')
insideEscaped = !insideEscaped;
// we need to split only on spaces which are not in "escaped" area
if (ch == ' ' && !insideEscaped) {
if (sb.length() > 0) {
tokens.add(sb.toString());
sb.delete(0, sb.length());
}
} else //and add characters that are not spaces from between \
sb.append(ch);
}
if (sb.length() > 0)
tokens.add(sb.toString());
return tokens;
}
Usage:
for (String s : spaceSplit("hello \\wo rld\\"))
System.out.println(s);
Output:
hello
\wo rld\