java 中使用正则匹配标签

第一类:单标签的匹配正则,以br为例:
Pattern p1 = Pattern.compile("<br\\s[^>]*>(.*?)(\\/> || >)");

Matcher m1 = p1.matcher(content);

while(m1.find()) {

//匹配到的内容

    String before_replace_tag = m1.group();

    if(before_replace_tag.length()>4){

log.info("已替换的内容是:" + before_replace_tag);

        content = content.replace(before_replace_tag,"");

    }else {

log.info( before_replace_tag +" 未达到替换标准,不进行替换!" );

    }

}

ps:其中的 (\\/> || >) 代表同时匹配有关闭符号和无关闭符号的,[^>]表示不是“>”的字符,*表示重复零次或更多次,这个意思是非“>”的字符可以有一个或多个,也可以没有。

可以匹配到的内容有下面这种样式的:

<br style="box-sizing: inherit;text-align: center;">

<br style="box-sizing: inherit; padding: 0px; list-style-type: none; outline: none !important;"/>

<br style="box-sizing: inherit; padding: 0px; list-style-type: none; outline: none !important;">

第二类:双标签的匹配,以a标签为例:

Pattern p1 = Pattern.compile("<a\\s[^>]*>(.*?)<\\/a>");

            Matcher m1 = p1.matcher(html);

            while(m1.find()) {

                String before_replace_tag = m1.group() ;

                int start_index = before_replace_tag.indexOf(">");

                int end_index = before_replace_tag.indexOf("</a>") ;

                String after_replace_tag = before_replace_tag ;

                if(start_index != -1 && end_index!= -1 && end_index > start_index){

                    after_replace_tag = before_replace_tag.substring(start_index + 1,end_index) ;

                }

                html = html.replace(before_replace_tag,after_replace_tag) ;

            }

ps:可以匹配到任何的url。

常用正则的匹配理解:

后边多一个?表示懒惰模式。

必须跟在*或者+后边用

如:<img src="test.jpg" width="60px" height="80px"/>

如果用正则匹配src中内容非懒惰模式匹配

src=".*"

匹配结果是:src="test.jpg" width="60px" height="80px"

意思是从="往后匹配,直到最后一个"匹配结束

懒惰模式正则:

src=".*?"

结果:src="test.jpg"

因为匹配到第一个"就结束了一次匹配。不会继续向后匹配。因为他懒惰嘛。

.表示除\n之外的任意字符

*表示匹配0-无穷

+表示匹配1-无穷

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,981评论 19 139
  • 1.常用类 1.1、Object类 Object是所有对象的直接或者间接父类,也就是上帝啦!该类中定义的肯定是所有...
    耑意儿阅读 220评论 0 0
  • String类和正则表达式 今天的主要内容 Scanner类概述Scanner获取数据出现的小问题及解决方案 St...
    须臾之北阅读 1,955评论 0 3
  • 1.应用技术 使用java.util.regex包下的Pattern和Matcher两个类 Pattern类创建正...
    嘻洋洋阅读 1,439评论 0 0
  • 正则表达 参考正则表达式的一个参考2 限定符 常用这个代替 x*,零次或多次 ≡{0,} {n,m}表示前面的...
    xmlovecm阅读 1,182评论 0 0