Java 中 MatchResult end() 方法附帶示例。


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

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

此介面的 end() 方法返回最近一次匹配發生後的偏移量。

示例

 即時演示

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 = "you$";
      //Reading input from user
      Scanner sc = new Scanner(System.in);
      String input = "Hello how are you";
      //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();
      System.out.println(end);
   }
}

輸出

Enter input text:
hello how are you
Match found
17

更新於: 10-Jan-2020

58 次瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.