溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java如何去掉html標(biāo)簽

發(fā)布時(shí)間:2021-03-29 12:11:36 來源:億速云 閱讀:222 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)java如何去掉html標(biāo)簽的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

java去掉html標(biāo)簽的方法:1、通過純正則方法去掉html標(biāo)簽;2、使用“javax.swing.text.html.HTMLEditorKit”去掉html標(biāo)簽;3、通過使用Jsoup框架去掉html標(biāo)簽等等。

一、背景

業(yè)務(wù)開發(fā)中可能需要將html的標(biāo)簽全部去掉,本文將多種方法綜合在這里,供大家參考。

二、方法

2.1 純正則方法

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class HTMLSpirit{ 
    public static String delHTMLTag(String htmlStr){ 
        String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/script>"; //定義script的正則表達(dá)式 
        String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //定義style的正則表達(dá)式 
        String regEx_html="<[^>]+>"; //定義HTML標(biāo)簽的正則表達(dá)式 
         
        Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE); 
        Matcher m_script=p_script.matcher(htmlStr); 
        htmlStr=m_script.replaceAll(""); //過濾script標(biāo)簽 
         
        Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE); 
        Matcher m_style=p_style.matcher(htmlStr); 
        htmlStr=m_style.replaceAll(""); //過濾style標(biāo)簽 
         
        Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE); 
        Matcher m_html=p_html.matcher(htmlStr); 
        htmlStr=m_html.replaceAll(""); //過濾html標(biāo)簽 

        return htmlStr.trim(); //返回文本字符串 
    } 
}

2.2 使用  javax.swing.text.html.HTMLEditorKit

import java.io.IOException;
import java.io.FileReader;
import java.io.Reader;
import java.util.List;
import java.util.ArrayList;

import javax.swing.text.html.parser.ParserDelegator;
import javax.swing.text.html.HTMLEditorKit.ParserCallback;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.MutableAttributeSet;

public class HTMLUtils {
  private HTMLUtils() {}

  public static List<String> extractText(Reader reader) throws IOException {
    final ArrayList<String> list = new ArrayList<String>();

    ParserDelegator parserDelegator = new ParserDelegator();
    ParserCallback parserCallback = new ParserCallback() {
      public void handleText(final char[] data, final int pos) {
        list.add(new String(data));
      }
      public void handleStartTag(Tag tag, MutableAttributeSet attribute, int pos) { }
      public void handleEndTag(Tag t, final int pos) {  }
      public void handleSimpleTag(Tag t, MutableAttributeSet a, final int pos) { }
      public void handleComment(final char[] data, final int pos) { }
      public void handleError(final java.lang.String errMsg, final int pos) { }
    };
    parserDelegator.parse(reader, parserCallback, true);
    return list;
  }

  public final static void main(String[] args) throws Exception{
    FileReader reader = new FileReader("java-new.html");
    List<String> lines = HTMLUtils.extractText(reader);
    for (String line : lines) {
      System.out.println(line);
    }
  }
}

【推薦:java視頻教程】

2.3 使用Jsoup框架

import java.io.IOException;
import java.io.FileReader;
import java.io.Reader;
import java.io.BufferedReader;
import org.jsoup.Jsoup;

public class HTMLUtils {
  private HTMLUtils() {}

  public static String extractText(Reader reader) throws IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader br = new BufferedReader(reader);
    String line;
    while ( (line=br.readLine()) != null) {
      sb.append(line);
    }
    String textOnly = Jsoup.parse(sb.toString()).text();
    return textOnly;
  }

  public final static void main(String[] args) throws Exception{
    FileReader reader = new FileReader
          ("C:/RealHowTo/topics/java-language.html");
    System.out.println(HTMLUtils.extractText(reader));
  }

2.4 使用Apache Tika

mport java.io.FileInputStream;
import java.io.InputStream;

import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;

public class ParseHTMLWithTika {
  public static void main(String args[]) throws Exception {

    InputStream is = null;
    try {

         is = new FileInputStream("C:/Temp/java-x.html");
        WriteOutContentHandler contenthandler = new WriteOutContentHandler(100000000);
         Metadata metadata = new Metadata();
         Parser parser = new AutoDetectParser();
         parser.parse(is, contenthandler, metadata, new ParseContext());
         System.out.println(contenthandler.toString());
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    finally {
        if (is != null) is.close();
    }
  }
}

注意這里經(jīng)過本人實(shí)驗(yàn)有個(gè)小坑,WriteOutContentHandler參數(shù)是限制的字符數(shù),這個(gè)如果不設(shè)置默認(rèn)是1萬,超過會(huì)報(bào)異常。

具體的jar包請(qǐng)自行到中央倉(cāng)庫(kù)里搜索依賴配置

https://search.maven.org/  和 https://mvnrepository.com/

三、提供一個(gè)工具類

可以將資源路徑的文本類型文件(如json/html)讀取成字符串

public class ResourceUtil {
    /**
     * 根據(jù)當(dāng)前類路徑,獲取資源文件夾對(duì)應(yīng)文件的所有字符串
     *
     * @param currentClass 如 this.class
     * @param resourcePath 如 /data/json/xxx.json (相對(duì)于resources文件夾)
     */
    public static String resource2String(Class currentClass, String resourcePath) throws IOException {
        return IOUtils.toString(new FileReader(new File(currentClass.getResource(resourcePath).getFile())));
    }

}

感謝各位的閱讀!關(guān)于“java如何去掉html標(biāo)簽”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI