Cael Cael - 6 months ago 11
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";


into

[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

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()) {
    System.out.println(String.format("'%s'", m.group(1)));
}

Ideone.com

Out

'chill hit donkey'
'chicken car roast'
'pink rat tree'
Comments