Java如何删除标签
删除HTML标签的方法
使用正则表达式可以快速删除HTML标签。以下代码示例展示了如何通过正则表达式移除字符串中的HTML标签:
String html = "<p>Hello, <b>world</b>!</p>";
String plainText = html.replaceAll("<[^>]*>", "");
System.out.println(plainText); // 输出: Hello, world!
使用Jsoup库处理HTML
Jsoup是一个专门用于处理HTML的Java库,提供了更安全可靠的方式来移除标签:
import org.jsoup.Jsoup;
String html = "<div>Sample <span>text</span></div>";
String plainText = Jsoup.parse(html).text();
System.out.println(plainText); // 输出: Sample text
保留特定标签的删除方法
如果需要保留某些特定标签,可以结合正则表达式和条件判断:
String html = "<p>Keep <b>this</b> but remove <i>that</i></p>";
String result = html.replaceAll("<(?!b\\s*\\b)[^>]*>", "");
System.out.println(result); // 输出: <p>Keep <b>this</b> but remove that</p>
处理XML标签的删除
对于XML文档,可以使用DOM解析器来移除标签:

import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
String xml = "<root><item>content</item></root>";
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
NodeList nodes = doc.getElementsByTagName("item");
String content = nodes.item(0).getTextContent();
System.out.println(content); // 输出: content
注意事项
正则表达式方法虽然简单,但对于复杂的HTML可能不够健壮。Jsoup库能更好地处理格式不规范的HTML文档。在性能敏感的场景中,可以考虑使用StringBuilder进行手动解析。






