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

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

<시간/>

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

usePattern() Matcher 클래스의 메서드는 새 정규식 패턴을 나타내는 Pattern 개체를 수락하고 일치 항목을 찾는 데 사용합니다.

예시

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UsePatternExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[#%&*]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //Retrieving Pattern used
      System.out.println("The are "+count+" special characters [# % & *] in the given text");
      //Building a pattern to accept 5 t 6 characters
      Pattern newPattern = Pattern.compile("\\A(?=\\w{6,15}\\z)");
      //Switching to new pattern
      matcher = matcher.usePattern(newPattern);
      if(matcher.find()) {
         System.out.println("Given input contain 6 to 15 characters");
      } else {
         System.out.println("Given input doesn't contain 6 to 15 characters");
      }
   }
}

출력

Enter input text:
#*mypassword&
The are 3 special characters [# % & *] in the given text
!!mypassword!
Given input doesn't contain 6 to 15 characters