Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

예제가 있는 Java의 Matcher hasTransparentBounds() 메서드

<시간/>

java.util.regex.Matcher 클래스는 다양한 일치 작업을 수행하는 엔진을 나타냅니다. 이 클래스에 대한 생성자가 없습니다. java.util.regex.Pattern 클래스의 match() 메소드를 사용하여 이 클래스의 객체를 생성/얻을 수 있습니다.

정규식에서 lookbehind 및 lookahead 구문은 다른 패턴 앞에 있거나 뒤따르는 특정 패턴을 일치시키는 데 사용됩니다. 예를 들어, 5~12개의 문자를 허용하는 문자열을 허용해야 하는 경우 정규식은 -

가 됩니다.
"\\A(?=\\w{6,10}\\z)";

기본적으로 매처 영역의 경계는 lookahead, lookbehind 및 경계 일치 구성에 투명하지 않습니다. 즉, 이러한 구성은 영역 경계를 넘어 입력 텍스트의 내용과 일치할 수 없습니다 -

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