直接上代碼:
package com.dajiangtai.djt_spider.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherTest {
public static void main(String[] args)
throws Exception {
Pattern p = Pattern.compile("(ca)(t)");
Matcher m = p.matcher("one cat,two cats in the yard");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
System.out.println("該次查找獲得匹配組的數量為:"+m.groupCount()); //2
for(int i=0;i<=m.groupCount();i++){
System.out.println("第"+i+"組的子串內容為:"+m.group(i));
}
}
}
輸出:
該次查找獲得匹配組的數量為:2
第0組的子串內容為:cat
第1組的子串內容為:ca
第2組的子串內容為:t
可以這樣理解:m.groupCount()表示()的個數。
m.group(0)表示要匹配滿足正則表達式中所有括號里的字符串的第一個值,因此為cat
m.group(1)表示匹配正則表達式中的第一個括號里的內容即可,因此為ca,注意,也是第一次的值
m.group(2)表示匹配正則表達式中的第二個括號里的內容即可,因此為t,注意,也是第一次的值