Java 中帶有示例的 Matcher regionEnd() 方法


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

此(Matcher)類的 regionEnd() 方法返回一個整數值表示當前匹配器物件的結束索引。

示例 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionEndExample {
   public static void main(String[] args) {
      String regex = "(.*)(\d+)(.*)";
      String input = "This is a sample Text, 1234, with numbers in between.";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      //Setting the region of the matcher
      matcher.region(5, 20);
      if(matcher.matches()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
      System.out.print("End of the region: "+matcher.regionEnd());
   }
}

輸出

Match not found
End of the region: 20

示例 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionEndExample {
   public static void main(String[] args) {
      //Regular expression to accepts 6 to 10 characters
      String regex = "[#]";
      System.out.println("Enter a string: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      //Setting region to the input string
      matcher.region(2, 4);
      //Switching to transparent bounds
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
      System.out.println("Ending of the region: "+ matcher.regionEnd());
   }
}

輸出

Enter a string:
this is sample text #
Match not found
Ending of the region: 4

更新於: 20-11-2019

102 檢視

開啟你的 職業生涯

透過完成課程取得認證

開始
廣告