【问题标题】:Extract all HTML tags, including closing tags, from file using Java without using external library like Jsoup使用 Java 从文件中提取所有 HTML 标记,包括结束标记,而不使用 Jsoup 等外部库
【发布时间】:2015-02-06 12:56:52
【问题描述】:

我有这段代码,它将接收一个 HTML 文件,获取所有打开的 HTML 标记,然后打印它们。我想知道是否有办法在这段代码中也包含结束标签。所以现在它打印:

<html>
<head>
<title>
<body>
<table>
<p>
<a>
<p>
etc. etc.

我也在寻找它与结束标签一起打印。

<p>
<a>
</a>
</p>

这是我到目前为止的代码:

        try {
        BufferedReader in = new BufferedReader(new FileReader("test.html"));
        String line;
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = in.readLine()) != null) {
            stringBuilder.append(line);
        }
        String pageContent = stringBuilder.toString();
        Pattern pattern = Pattern.compile("<(?!!)(?!/)\\s*([a-zA-Z0-9]+)(.*?)>");
        Matcher matcher = pattern.matcher(pageContent);
        while (matcher.find()) {
            String tagName = matcher.group(1);
            System.out.println("<" + tagName + ">");
        }
        in.close();
    }

编辑:有没有办法在不使用 Jsoup 之类的外部库的情况下做到这一点? 编辑 2:我将 Pattern.compile 更改为 this-> 并且它有效。谢谢。

【问题讨论】:

标签: java html regex file-io


【解决方案1】:

如果可以使用外部库,您可以按照此处所述使用 JSoup。 Extract Tags from a html file using Jsoup

【讨论】:

猜你喜欢
  • 2013-11-23
  • 2020-08-28
  • 1970-01-01
  • 1970-01-01
  • 2015-04-24
  • 2016-10-02
  • 2013-04-03
  • 2020-04-29
  • 1970-01-01
相关资源
最近更新 更多