---
title: "正则表达式 Matcher的 group, start, end 等用法"
author: "ezfantasy"
date: "2015-08-19T12:57:11Z"
tags: []
categories: ["编程语言"]
slug: "matcher-group-start-end"
draft: false
lastmod: "2015-08-19T12:57:11Z"
id: 2236524
url: "https://ezfantasy.iteye.com/blog/2236524"
---

```
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 : &lt;img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E\_\_\_0173EN00SIGT.gif" style="margin:1px;" border="0" title="灌水" /&gt;

0173EN00SIG

灌水

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

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

\[emoticons=E\_\_\_0088EN00SIGT]顶\[/emoticons]

target : &lt;img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E\_\_\_0088EN00SIGTT.gif" style="margin:1px;" border="0" title="顶" /&gt;

0088EN00SIGT

顶

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

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

\[emoticons=E\_\_\_0177EN00SIGT]飘过\[/emoticons]

target : &lt;img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E\_\_\_0177EN00SIGTT.gif" style="margin:1px;" border="0" title="飘过" /&gt;

0177EN00SIGT

飘过

最后的结果：哈哈&lt;img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E\_\_\_0173EN00SIGT.gif" style="margin:1px;" border="0" title="灌水" /&gt;沙发&lt;img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E\_\_\_0088EN00SIGTT.gif" style="margin:1px;" border="0" title="顶" /&gt;顶你飘过~&lt;img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E\_\_\_0177EN00SIGTT.gif" style="margin:1px;" border="0" title="飘过" /&gt;

 

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