group是針對括號()來說的,group(0)就是指的整個串,group(1) 指的是第一個括號里的東西,group(2)指的第二個括號里的東西。
上代碼:
1 @Test 2 public void test1() { 3 Pattern pattern = Pattern.compile("頁面下載失敗\\.url:\\[http://[a-z0-9]+\\.(.+)/.+\\]\\.當前時間戳:\\[([0-9]+)\\]"); 4 Matcher matcher = pattern.matcher("頁面下載失敗.url:[http://item.jd.com/15626278.html].當前時間戳:[1471415298943]"); 5 if(matcher.find()){ 6 String top_domain = matcher.group(1); 7 String curr_time = matcher.group(2); 8 System.out.println(top_domain+"--"+"--"+curr_time);//jd.com----1471415298943 9 } 10 } 11 12 @Test 13 public void test2(){ 14 String url = "https://item.jd.com/698763154.html"; 15 Pattern pattern = Pattern.compile("https://item.jd.com/([0-9]+).html"); 16 Matcher matcher = pattern.matcher(url); 17 if(matcher.find()){ 18 System.out.println(matcher.group(1));//698763154 19 System.out.println(matcher.group(0));//https://item.jd.com/698763154.html 20 } 21 } 22 23 @Test 24 public void test3(){ 25 String str = "Hello,World! in Java."; 26 Pattern pattern = Pattern.compile("W(or)(ld!)"); 27 Matcher matcher = pattern.matcher(str); 28 while(matcher.find()){ 29 System.out.println("Group 0:"+matcher.group(0));//得到第0組——整個匹配 30 System.out.println("Group 1:"+matcher.group(1));//得到第一組匹配——與(or)匹配的 31 System.out.println("Group 2:"+matcher.group(2));//得到第二組匹配——與(ld!)匹配的,組也就是子表達式 32 System.out.println("Start 0:"+matcher.start(0)+" End 0:"+matcher.end(0));//總匹配的索引 33 System.out.println("Start 1:"+matcher.start(1)+" End 1:"+matcher.end(1));//第一組匹配的索引 34 System.out.println("Start 2:"+matcher.start(2)+" End 2:"+matcher.end(2));//第二組匹配的索引 35 System.out.println(str.substring(matcher.start(0),matcher.end(1)));//從總匹配開始索引到第1組匹配的結束索引之間子串——Wor 36 } 37 }
總結:其實group(),start(),end()所帶的參數i就是正則表達式中的子表達式索引(第幾個子表達式)。