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: 如果正则表达式写的臃肿,低效,请高人帮忙优化吧,菜鸟我每次用都是现查