matcher 類 group(int i) shart(int i) end(int i)用法

group(int i):正則表達式匹配的第i個子表達式,若是i是0,則所有匹配java

start(int i):匹配第i個子正則表達式的字符串的第一個字符所在位置的下標正則表達式

end(int i):匹配第i個子正則表達式的字符串的最後一個字符所在位置的下標+1spa

例子:code

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  
   }  
}  
  
}  



運行結果:
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
相關文章
相關標籤/搜索