MatchResult end(int group) 方式在 Java 中並有例子說明。


java.util.regex.MatcheResult 介面提供了檢索匹配結果的方法。

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

此介面的 end(int group) 方法接受一個表示特定組的整數,並返回指定組中最後一次匹配發生後的偏移量。

示例

 即時演示

import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   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();
      int end = res.end(1);
      System.out.println(end);
   }
}

輸出

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

更新於:2020-01-10

52 次瀏覽

啟動你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.