Java 的 Matcher hasTransparentBounds() 方法附帶示例


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

在正則表示式中,後向和前向構建用於匹配在其他模式中,在一些其他模式中先行或後續的特定模式。例如,如果您需要接受一個接受 5 到 12 個字元的字串,則正則表示式為 −

"\A(?=\w{6,10}\z)";

預設情況下,匹配器區域的邊界對於構建前向、後向和邊界匹配不透明,即這些構建不能匹配超出門區域邊界的輸入文字內容 −

此類的 hasTransparentBounds() 方法驗證當前匹配器是否使用透明邊界,如果是,則返回 true,否則,返回 false。

示例 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HasTransparentBounds {
   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);
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
      boolean bool = matcher.hasTransparentBounds();
      //Switching to transparent bounds
      if(bool) {
         System.out.println("Current matcher uses transparent bounds");
      } else {
         System.out.println("Current matcher user non-transparent bound");
      }
   }
}

輸出

Enter 5 to 12 characters:
sampletext
Match not found
Current matcher user non-transparent bound

示例 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HasTransparentBounds {
   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);
      matcher.useTransparentBounds(true);
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
      boolean bool = matcher.hasTransparentBounds();
      //Switching to transparent bounds
      if(bool) {
         System.out.println("Current matcher uses transparent bounds");
      } else {
         System.out.println("Current matcher user non-transparent bound");
      }
   }
}

輸出

Enter 5 to 12 characters:
sampletext
Match found
Current matcher uses transparent bounds

更新於: 20-Nov-2019

50 次瀏覽

助力 職業發展

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.