Log4X

链路纵横
[搬家文]java的regex.Matcher 使用一例(group()方法用法)

关于pattern,matcher的各个函数有javadoc没啥好说的。

不过还是有一点需要强调强调,第一是这个group,其实有groupCount+1组

group(0)对应的是整个正则表达式匹配部分,group(1)~group(groupCount)则是小括号内匹配部分。

而且这个分组的对象,是一次find以后,正则表达式匹配到的那一段字符串

比如一个String ,(s1)xxx(s2)有s1,s2两部分符合要求,那么一次find以后,所有group都是在S1内部的

第二次find后,所有group都是在S2内部的内容

 

 1 import java.util.regex.Matcher;
 2 import java.util.regex.Pattern;
 3 
 4 public class RegexTest {
 5 
 6 public static void printMatched(String regex, String source) {
 7    Pattern p = Pattern.compile(regex);
 8    Matcher m = p.matcher(source);
 9    while (m.find()) {
10     for (int i = 0; i <= m.groupCount(); i++) {
11      System.out.println(m.group(i));
12     }
13    }
14 }
15 
16 public static void main(String[] arg) {
17    RegexTest.printMatched("<(\\w+)>.*</(\\1)>",
18      "<table><td>sdjfjfiweif</td></table><cd>sdfsdf</cd>");
19 
20 }
21 }
22 

 

[2008-8-13补充]java中String有replace,replaceAll两个方法,其实都是对所有匹配项进行替换。只是replaceAll支持正则表达式。

很多人拿replaceAll当replace用,出问题了还不知道怎么回事。

posted on 2008-08-13 19:14  YYX  阅读(6533)  评论(1编辑  收藏  举报