正则匹配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]*>

作者:林宇风
版权所有,侵权必究!标明出处,欢迎转载。
原文地址:https://www.cnblogs.com/linyufeng/p/14370936.html