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  w  ww .  j a v a2  s .  c o  m*/

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

truncate After Words using regex

Related Exercise