正则表达式 Matcher的 group, start, end 等用法

public static void main(String[] args) {
		String str = "哈哈[emoticons=E___0173EN00SIG]灌水[/emoticons]沙发" +
        		"[emoticons=E___0088EN00SIGT]顶[/emoticons]顶你" +
        		"飘过~[emoticons=E___0177EN00SIGT]飘过[/emoticons]";
        Pattern p = Pattern.compile("\\[emoticons=E___([0-9a-zA-Z]*)](.*?)\\[\\/emoticons]");
        String s = "<img src=\"http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___%1$sT.gif\" style=\"margin:1px;\" border=\"0\" title=\"%2$s\" />";
        
    	
        Matcher m = p.matcher(str);
        String source, target;
        while (m.find()) {
        	System.out.println("每个匹配结果的起始位置: " + m.start());
        	System.out.println("每个匹配结果的结束位置: " + m.end());
        	source = m.group(0);
        	System.out.println(source);	//全量
        	target = String.format(s, m.group(1), m.group(2));
        	System.out.println("target : " + target);
        	System.out.println(m.group(1));	//第一个
        	System.out.println(m.group(2));	//第二个
        	str = str.replace(source, target);
        } 
        System.out.println("最后的结果:" + str);
	}

 输出结果:

每个匹配结果的起始位置: 2

每个匹配结果的结束位置: 43

[emoticons=E___0173EN00SIG]灌水[/emoticons]

target : <img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0173EN00SIGT.gif" style="margin:1px;" border="0" title="灌水" />

0173EN00SIG

灌水

每个匹配结果的起始位置: 45

每个匹配结果的结束位置: 86

[emoticons=E___0088EN00SIGT]顶[/emoticons]

target : <img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0088EN00SIGTT.gif" style="margin:1px;" border="0" title="顶" />

0088EN00SIGT

每个匹配结果的起始位置: 91

每个匹配结果的结束位置: 133

[emoticons=E___0177EN00SIGT]飘过[/emoticons]

target : <img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0177EN00SIGTT.gif" style="margin:1px;" border="0" title="飘过" />

0177EN00SIGT

飘过

最后的结果:哈哈<img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0173EN00SIGT.gif" style="margin:1px;" border="0" title="灌水" />沙发<img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0088EN00SIGTT.gif" style="margin:1px;" border="0" title="顶" />顶你飘过~<img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0177EN00SIGTT.gif" style="margin:1px;" border="0" title="飘过" />

 

PS: 如果正则表达式写的臃肿,低效,请高人帮忙优化吧,菜鸟我每次用都是现查

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值