Java - truncate After Words using regex

Description

truncate After Words using regex

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        int numberOfWords = 42;
        String longString = "this is a test this is a test this is a test this is a test this is a test this is a test ";
        System.out.println(truncateAfterWords(numberOfWords, longString));
    }//from  ww  w. ja v  a2 s  .co m

    public static String truncateAfterWords(int numberOfWords,
            String longString) {
        return longString.replaceAll("^((?:\\W*\\w+){" + numberOfWords
                + "}).*$", "$1");
    }
}

truncate After Words using regex