How do I find text between two strings?
Category: Commons Lang, viewed: 1662 time(s).
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
Can't find what you are looking for? Join our FORUMS and ask some questions!
Related Examples
- How do I check for an empty string?
- How do I get the nearest hour, minute, second of a date?
- How do I format date and time using DateFormatUtils class?
- How do I find items in an array?
- How do I use CompareToBuilder class?
- How do I use ReflectionToStringBuilder class?
- How do I convert array of object to array of primitive?
- How do I convert an array to a Map?
- How do I reverse array elements order?
- How do I count word occurrences in a string?