原來,group是針對()來說的,group(0)就是指的整個串,group(1) 指的是第一個括號裏的東西,group(2)指的第二個括號裏的東西。
程序如下
Java代碼 收藏代碼
package cn.mingyuan.regexp.singlecharacter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupIndexAndStartEndIndexTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "Hello,World! in Java.";
Pattern pattern = Pattern.compile("W(or)(ld!)");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
System.out.println("Group 0:"+matcher.group(0));//得到第0組——整個匹配
System.out.println("Group 1:"+matcher.group(1));//得到第一組匹配——與(or)匹配的
System.out.println("Group 2:"+matcher.group(2));//得到第二組匹配——與(ld!)匹配的,組也就是子表達式
System.out.println("Start 0:"+matcher.start(0)+" End 0:"+matcher.end(0));//總匹配的索引
System.out.println("Start 1:"+matcher.start(1)+" End 1:"+matcher.end(1));//第一組匹配的索引
System.out.println("Start 2:"+matcher.start(2)+" End 2:"+matcher.end(2));//第二組匹配的索引
System.out.println(str.substring(matcher.start(0),matcher.end(1)));//從總匹配開始索引到第1組匹配的結束索引之間子串——Wor
}
}
}
程序的運行結果爲:
Java代碼 收藏代碼
Group 0:World!
Group 1:or
Group 2:ld!
Start 0:6 End 0:12
Start 1:7 End 1:9
Start 2:9 End 2:12
Wor
總結:其實group(),start(),end()所帶的參數i就是正則表達式中的子表達式索引(第幾個子表達式),由於剛開始對Java正則表達式中的組的概念不清晰,導致理解困難。當將“組”的概念與“子表達式”對應起來之後,理解matcher的group,start,end就完全沒有障礙了。