正則匹配html標簽以及內容


  1. 匹配所有標簽 </?[a-zA-Z! ="-\d]*>

  2. 匹配閉合標簽以及里面內容 <[a-zA-Z! ="-\d]*>[^</>]*</[a-zA-Z! ="-\d]*>


java使用要對-進行轉義:

  • </?[a-zA-Z! ="\-\d]*>
  • <[a-zA-Z! ="\-\d]*>[^</>]*</[a-zA-Z! ="\-\d]*>
/**
 * @author linyufeng.
 * @date 2021/2/3 13:34
 **/
public class TextUtil {

    // 去除html標簽
    public static String disHtml(String str) {
        return str.replaceAll("</?[a-zA-Z! =\"\\-\\d]*>", "");
    }

    // 去除html標簽以及里面內容
    public static String disAllHtml(String str) {
        return str.replaceAll("<[a-zA-Z! =\"\\-\\d]*>[^</>]*</[a-zA-Z! =\"\\-\\d]*>", "");
    }

}
  • ((?!abc).)* 否定向前語法, 可以幫助我們去除指定前綴的字符串;
  • [^abc]范圍比較大,不能起到只過濾abc的目的;

所以,上述優化格式為: <[a-zA-Z! ="\-\d]*>((?!</).)*</[a-zA-Z! ="\-\d]*>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM