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.lang3.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: Wed Jul 24 10:34:49 WITA 2019
Maven Dependencies
<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019
Hi, How to get text between a tag like
<a href rel="nofollow">some text here</a>
Wont work because
<a>
has some attributes inside.Hi Richa,
You can try using regex as the following example: