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

posted @ 2021-02-04 09:50  林宇风  阅读(1581)  评论(0编辑  收藏  举报