Matcher region(int start, int end) 方法在 Java 中,帶示例


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

這個 (Matcher) 類的 region() 方法接受兩個表示輸入字串中位置的整數值,並設定當前匹配器的區域。

範例 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionExample {
   public static void main(String[] args) {
      //Regular expression to accepts 6 to 10 characters
      String regex = "\A(?=\w{6,10}\z)";
      System.out.println("Enter 5 to 12 characters: ");
      String input = new Scanner(System.in).next();
      //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(0, 4);
      //Switching to transparent bounds
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

輸出

Enter 5 to 12 characters:
sampleText
Match not found

範例 2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionExample {
   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(0, 20);
      if(matcher.matches()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

輸出

Match not found

更新於: 2019 年 11 月 20 日

149 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.