Matcher end() 方法及其在 Java 中的示例


java.util.regex.Matcher 類表示用於執行各種匹配操作的引擎。此類沒有建構函式,你可以使用類 java.util.regex.Pattern 的 matches() 方法建立/獲取此類的物件。

Matcher 類的 end() 方法返回當前物件表示的上次匹配後的偏移量。

子表示式 "[...]" 匹配輸入字串中花括號內的字元,在以下示例中,用此方法匹配字元 t。此處:

  • 我們使用 compile() 方法編譯了正則表示式。

  • 獲取了 Matcher 物件。

  • 對每次匹配呼叫 matcher() 方法。

示例

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EndExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[t]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while (matcher.find()) {
         int end = matcher.end();
         System.out.println(end);
      }
   }
}

輸出

Enter input text:
Hello how are you welcome to Tutorialspoint
27
32
43

由於字元 t 在輸入字串中出現了三次,你可以看到三個偏移量值(表示每次出現後在輸入字串中的位置)。

更新於: 19-11-2019

215 次瀏覽

開啟你的事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.