Get n Number of words using regex in Java

Posted by Aymon Fournier on Stack Overflow See other posts from Stack Overflow or by Aymon Fournier
Published on 2010-05-08T07:47:58Z Indexed on 2010/05/08 7:58 UTC
Read the original article Hit count: 162

Filed under:
|
|
|
|

I have a section of a book, complete with punctuation, line breaks etc. and I want to be able to extract the first n words from the text, and divide that into 5 parts. Regex mystifies me. This is what I am trying. I creates an array of index size 0, with all the input text:

public static String getNumberWords2(String s, int nWords){
String[] m = s.split("([a-zA-Z_0-9]+\b.*?)", (nWords / 5));
return "Part One: \n" + m[1] + "\n\n" + "Part Two: \n" + m[2] +
"\n\n" + "Part Three: \n" + m[3] + "\n\n"  + "Part Four: \n" + m[4] + "\n\n"
 + "Part Five: \n" + m[5];

}

Thanks!

© Stack Overflow or respective owner

Related posts about java

Related posts about regex