English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java의 Matcher usePattern() 메서드와 예제

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

Matcher 클래스의usePattern()메서드는 새 정규 표현식 패턴을 나타내는 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 = "[#%&*]";
      //create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //create a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      //search pattern used
      System.out.println("The are "+count+" special characters [# % & *] in the given text");
      //to establish an acceptance5 t 6character pattern
      Pattern newPattern = Pattern.compile("\\A(?=\\w{6,15}\\z)");
      //switch to new mode
      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
추천해드립니다