2. 使用正则表达式

既然HTML内容已作为字符串变量存在,我们需要进行文本操作。面对这类问题,正则表达式(Regex)通常是首选方案。

移除HTML标签对Regex来说并不复杂——无论标签开头还是结尾,都遵循< ... >的模式。对应的正则表达式可以是:

  • <[^>]*>(匹配尖括号内非>的任意字符)
  • <.*?>(非贪婪匹配任意字符)

踩坑提示:Regex默认采用贪婪匹配<.*>会匹配从第一个<到最后一个>的内容,这会导致错误结果。必须使用非贪婪模式<.*?>

2.1. 从 example1.html 移除标签

先创建测试HTML文件(example1.html):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>This is the page title</title>
</head>
<body>
    <p>
        If the application X doesn't start, the possible causes could be:<br/>
        1. <a href="maven.com">Maven</a> is not installed.<br/>
        2. Not enough disk space.<br/>
        3. Not enough memory.
    </p>
</body>
</html>

使用String.replaceAll()移除标签:

String html = ... // 加载example1.html
String result = html.replaceAll("<[^>]*>", "");
System.out.println(result);

输出结果(已移除多余空行):

    This is the page title


    
        If the application X doesn't start, the possible causes could be:
        1. Maven is not installed.
        2. Not enough disk space.
        3. Not enough memory.

效果不错——所有HTML标签都被移除,但保留了原始空白字符。后续处理时可以轻松清理这些空行。

2.2. 从 example2.html 移除标签

正则表达式方案存在致命缺陷:无法处理所有可能的HTML结构。比如:

  • <script><style>标签的内容可能需要排除
  • 标签内容中可能包含<>字符(如比较运算符)

测试用example2.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>This is the page title</title>
</head>
<script>
    // some interesting script functions
</script>
<body>
    <p>
        If the application X doesn't start, the possible causes could be:<br/>
        1. <a
            id="link"
            href="http://maven.apache.org/">
            Maven
            </a> is not installed.<br/>
        2. Not enough (<1G) disk space.<br/>
        3. Not enough (<64MB) memory.<br/>
    </p>
</body>
</html>

使用相同正则表达式处理后的错误输出:

   This is the page title
    // some interesting script functions    
        If the application X doesn't start, the possible causes could be:
        1. 
            Maven
             is not installed.
        2. Not enough (
        3. Not enough (

结论:用Regex处理HTML/XML极其脆弱!遇到<>字符会破坏文本结构。建议改用专业HTML解析器。

3. 使用 Jsoup

Jsoup是流行的Java HTML解析器。提取文本只需一行代码:

Jsoup.parse(htmlString).text()

添加Maven依赖:

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.17.2</version>
</dependency>

处理example2.html:

String html = ... // 加载example2.html
System.out.println(Jsoup.parse(html).text());

输出结果:

This is the page title If the application X doesn't start, the possible causes could be: 1. Maven is not installed. 2. Not enough (<1G) disk space. 3. Not enough (<64MB) memory.

核心优势

  • 自动忽略<script>等标签内容
  • 默认移除所有格式(包括换行符)
  • 正确处理特殊字符(如<1G

扩展:如需保留换行符,可配置Jsoup的换行处理机制

4. 使用 HTMLCleaner

HTMLCleaner专注于清理"不规范"的HTML,适合处理网页源码。

添加Maven依赖:

<dependency>
    <groupId>net.sourceforge.htmlcleaner</groupId>
    <artifactId>htmlcleaner</artifactId>
    <version>2.25</version>
</dependency>

处理example2.html(跳过script标签):

String html = ... // 加载example2.html
CleanerProperties props = new CleanerProperties();
props.setPruneTags("script"); // 忽略script标签
String result = new HtmlCleaner(props).clean(html).getText().toString();
System.out.println(result);

输出结果:

    This is the page title


    
        If the application X doesn't start, the possible causes could be:
        1. 
            Maven
             is not installed.
        2. Not enough (<1G) disk space.
        3. Not enough (<64MB) memory.

关键特性

  • <br/>转换为换行符
  • 保留原始空白字符(导致文本分行)
  • 支持通过CleanerProperties精细控制解析行为

适用场景:需要保留部分格式(如换行)时比Jsoup更灵活。

5. 使用 Jericho

Jericho提供独特的文本渲染功能,能保留部分HTML格式信息。

添加Maven依赖:

<dependency>
    <groupId>net.htmlparser.jericho</groupId>
    <artifactId>jericho-html</artifactId>
    <version>3.4</version>
</dependency>

提取文本并保留链接URL:

String html = ... // 加载example2.html
Source htmlSource = new Source(html);
Segment segment = new Segment(htmlSource, 0, htmlSource.length());
Renderer htmlRender = new Renderer(segment).setIncludeHyperlinkURLs(true);
System.out.println(htmlRender);

输出结果:

If the application X doesn't start, the possible causes could be:
1. Maven <http://maven.apache.org/> is not installed.
2. Not enough (<1G) disk space.
3. Not enough (<64MB) memory.

突出优势

  • 自动忽略<title>标签内容
  • 将链接渲染为文本 <URL>格式
  • 支持<br/><ul><li>等标签的格式化渲染
  • 保持文本可读性的同时保留关键结构信息

适用场景:需要提取超链接、列表等结构化信息时的最佳选择。

6. 结论

处理HTML文本提取时,避免使用正则表达式——它在复杂场景下会失效。推荐方案:

方案 适用场景 核心优势
Jsoup 纯文本提取 简单高效,自动过滤脚本/样式
HTMLCleaner 需保留部分格式 支持换行符转换,配置灵活
Jericho 需保留结构信息 渲染链接/列表,格式化输出

经验之谈:根据需求选择工具——纯文本用Jsoup,格式化输出用HTMLCleaner,结构化信息用Jericho。


原始标题:Remove HTML Tags Using Java | Baeldung