捕獲組是將多個字元視為一個單元的一種方法。 它們是通過將要分組的字元放在一組括號中來建立的。 例如,正規表示式(dog
)建立包含字母d
,o
和g
的單個組。
捕獲組通過從左到右計算它們的左括號來編號。 在表示式((A)(B(C))
)中,例如,有四個這樣的組 -
要查詢表示式中存在多少個組,請在匹配器物件上呼叫groupCount
方法。groupCount
方法返回一個int
,顯示匹配器模式中存在的捕獲組數。
還有一個特殊組,即組0
,它始終代表整個表示式。 該組未包含在groupCount
報告的總數中。
以下範例說明如何從給定的字母數位字串中查詢數位字串 -
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
public static void main( String args[] ) {
// String to be scanned to find the pattern.
String line = "This order was placed for QT3000! OK?";
String pattern = "(.*)(\d+)(.*)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
} else {
System.out.println("NO MATCH");
}
}
}
執行上面範例程式碼,得到以下結果:
Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT300
Found value: 0