Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Split a string at a single space

I am looking to split a string into an array of strings at every single space.

For example:

This_sentence_gets__split. (Underscores represent spaces here)





" " (note the double space was left as one space)


I assume I can do this with String.split(String regex) but I am not very good with regular expressions and I do not know how I would accomplish this.


Any spaces after the first should be split into substrings as well. For example: Split___this. becomes "Split " " " " "this."

like image 672
Ryan Jackman Avatar asked Feb 17 '23 20:02

Ryan Jackman

1 Answers

I think this might be what you are looking for (you can improve it with \\s class for all whitespace like tabs, new lines and so on)

String data = "This_sentence__gets___split".replace('_', ' ');
// System.out.println(data);
String arr[] = data.split("(?<! ) |(?<= {2})");
for (String s : arr)
    System.out.println("\"" + s + "\"");


" "
" "
" "


  • "(?<! ) " will split only on spaces that don't have space before it
  • "(?<= {2})" will split in place that have two spaces before it.
like image 178
Pshemo Avatar answered Feb 28 '23 10:02