How to truncate a string after n number of words?

package org.kodejava.example.lang;

public class GetNumberOfWordsFromString {
    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog.";

        String one = truncateAfterWords(1, text);
        System.out.println("1 = " + one);

        String two = truncateAfterWords(2, text);
        System.out.println("2 = " + two);

        String four = truncateAfterWords(4, text);
        System.out.println("4 = " + four);

     * Truncate a string after n number of words.
     * @param numberOfWords number of words to truncate after.
     * @param longString the long string.
     * @return truncated long string.
    public static String truncateAfterWords(int numberOfWords, String longString)     {
        return longString.replaceAll("^((?:\W*\w+){" +
                numberOfWords + "}).*$", "$1");

The result of the snippet:

1 = The
2 = The quick
4 = The quick brown fox

How to remove non ASCII characters from a string?

The code snippet below remove the characters from a string that is not inside the range of x20 and x7E ASCII code. The regex below strips non-printable and control characters. But it also keeps the linefeed character n (x0A) and the carriage return r (x0D) characters.

package org.kodejava.example.regex;

public class ReplaceNonAscii {
    public static void main(String[] args) {
        String str = "Thè quïck brøwn føx jumps over the lãzy dôg.";
        System.out.println("str = " + str);

        // Replace all non ascii chars in the string.
        str = str.replaceAll("[^\x0A\x0D\x20-\x7E]", "");
        System.out.println("str = " + str);

Snippet output:

str = Thè quïck brøwn føx jumps over the lãzy dôg.
str = Th quck brwn fx jumps over the lzy dg.

How do I use possessive quantifier regex?

The possessive quantifiers always eat the entire input string, trying once (and only once) for a match. Unlike the greedy quantifiers, possessive quantifiers never back off, even if doing so would allow the overall match to succeed.

package org.kodejava.example.util.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PossessiveQuantifierDemo {
    public static void main(String[] args) {
        String[] regexs = {
        String input = "xxxxxxx";

        for (String r : regexs) {
            Pattern pattern = Pattern.compile(r);
            Matcher matcher = pattern.matcher(input);

            // Find every match and print it
            System.out.format("Regex:  %s %n", r);
            while (matcher.find()) {
                System.out.format("Text "%s" found at %d to %d.%n",
              , matcher.start(),