Java如何在两个字符串之间查找文本?
在此示例中,我们将使用StringUtils.substringBetween()方法。在这里,我们将提取HTML文档的标题和正文。让我们看一下代码。
package org.nhooo.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);
}
}通过打印标题和内容,我们将看到类似以下内容的内容:
title = Hello World from Java content = Hello, today is: Wed Jul 24 10:34:49 WITA 2019
Maven依赖
<!-- 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>