How do I find text between two strings?

In this example we’ll use the StringUtils.substringBetween() method. Here we’ll extract the title and body of our HTML document. Let’s see the code.

package org.kodejava.example.commons.lang;

import java.util.Date;
import org.apache.commons.lang.StringUtils;

public class NestedString {
    public static void main(String[] args) {
        String helloHtml = "<html>" +
                "<head>" +
                "   <title>Hello World from Java</title>" +
                "<body>" +
                "Hello, today is: " + new Date() +
                "</body>" +
                "</html>";

        String title = StringUtils.substringBetween(helloHtml, "<title>", "</title>");
        String content = StringUtils.substringBetween(helloHtml, "<body>", "</body>");

        System.out.println("title = " + title);
        System.out.println("content = " + content);
    }
}

By print out the title and content we’ll see something similar to:

title = Hello World from Java
content = Hello, today is: Tue Apr 08 07:02:39 ICT 2008

How do I count word occurrences in a string?

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.StringUtils;

public class WordCountExample {
    public static void main(String[] args) {
        // We have the source text we'll do the search on.
        String source = "From the download page, you can download the Java " +
                "Tutorials for browsing offline. Or you can just download " +
                "the examples.";
        // The word we want to count its occurrences
        String word = "you";

        // Using StringUtils.countMatches() method we can count the occurrences
        // frequency of a word/letter in the giver source of string.
        int wordFound = StringUtils.countMatches(source, word);

        // Print how many we have found the word
        System.out.println(wordFound + " occurrences of the word '" + word +
                "' was found in the text.");
    }
}

Here is the result of the code above.

2 occurrences of the word 'you' was found in the text.