Java Regex - 捕獲組



捕獲組是一種將多個字元視為一個單元的方法。透過將要分組的字元放在一組括號內來建立它們。例如,正則表示式 (dog) 建立了一個包含字母“d”、“o”和“g”的單個組。

捕獲組按從左到右的順序編號,依次計算其左括號。例如,在表示式 ((A)(B(C))) 中,有四個這樣的組 −

  • ((A)(B(C)))
  • (A)
  • (B(C))
  • (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
廣告