Cael Cael - 2 years ago 73
Java Question

String splitting on 3 or more words

I have a code that will split 2 words in a string and put them in a array.

String words = "chill hit donkey chicken car roast pink rat tree";


[chill hit, donkey chicken, car roast, pink rat, tree]

This is my code for that:

String[] result = joined.split("(?<!\\G\\S+)\\s");
System.out.printf("%s%n", Arrays.toString(result));

Now, how do I modify the regex so that it will split into 3 or more words?

Output(3 word in an array):

[chill hit donkey, chicken car roast, pink rat tree]

Output(4 word in an array):

[chill hit donkey chicken, car roast pink rat tree]

Tried to modify regex but nothing had worked this far. Thanks.

Answer Source

Here is one another find() version – just change {3} to whatever number you like.

Regex demo

// ((?:\w+\W?){3})(?:(\W+|$))
String text = "chill hit donkey chicken car roast pink rat tree";
String regex = "((?:\\w+\\W?){3})(?:(\\W+|$))";
Matcher m = Pattern.compile(regex).matcher(text);
while (m.find()) {


'chill hit donkey'
'chicken car roast'
'pink rat tree'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download