Java 中的 MatchResult group(int group) 方法及示例。


java.util.regex.MatcheResult 介面提供獲取匹配結果的方法

可以使用 Matcher 類的 toMatchResult() 方法來獲取這個介面的物件。這個方法返回一個 MatchResult 物件,該物件表示當前匹配器的匹配狀態。

此介面的 group(int group) 方法接受一個表示特定組的整數值,並返回一個字串值,表示在上次匹配期間,從指定輸入序列中的指定組匹配的子字串。

示例

 演示

import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupExample {
   public static void main( String args[] ) {
      String regex = "(.*)(\d+)(.*)";
      //Reading input from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      //Instantiating the Pattern class
      Pattern pattern = Pattern.compile(regex);
      //Instantiating the Matcher class
      Matcher matcher = pattern.matcher(input);
      //verifying whether a match occurred
      if(matcher.find()) {
         System.out.println("Match found");
      }
      MatchResult res = matcher.toMatchResult();
      String matchedData = res.group(2);
      System.out.println(matchedData);
   }
}

輸出

Enter input text:
This is a sample Text, 123
Match found
3

更新於: 2020-01-10

145 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.