Javaregex-matchresult-groupcount

提供:Dev Guides
移動先:案内検索

java.util.regex.MatchResult.groupCount

説明

  • java.time.MatchResult.groupCount()*メソッドは、この一致結果のパターンのキャプチャグループの数を返します。

宣言

以下は、* java.time.MatchResult.groupCount()*メソッドの宣言です。

int groupCount()

戻り値

このマッチャーのパターンのキャプチャグループの数。

次の例は、java.time.MatchResult.groupCount()メソッドの使用法を示しています。

package com.finddevguides;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatchResultDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
     //create a pattern
      Pattern pattern = Pattern.compile(REGEX);

     //get a matcher object
      Matcher matcher = pattern.matcher(INPUT);

      if(matcher.find()) {
        //get the MatchResult Object
         MatchResult result = matcher.toMatchResult();

        //Prints the number of capturing groups in this match result's pattern.
         System.out.println("Capturing Groups: "+result.groupCount());
      }
   }
}

上記のプログラムをコンパイルして実行すると、次の結果が生成されます-

First Capturing Group - Match String: This is a sample Text, 1234, with numbers in between.