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

Java에서 Matcher pattern() 메서드와 예제

Thisjava.util.regex.MatcherThis class represents an engine that performs various matching operations. This class has no constructor, and it can be used withmatches()Pattern class of java.util.regex created by the method/The object of this class can be obtained.

이 클래스(Matcher)의pattern()Method to get and return the Pattern (object) interpreted by the current Matcher.

예제1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your date of birth (MM/DD/YYY)
      String date = sc.next();
      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}";
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Create a Matcher object
      Matcher matcher = pattern.matcher(date);
      //Date validation
      if(matcher.matches())
         System.out.println("Date is valid");
      else
         System.out.println("Date is not valid");
      //Retrieval pattern used
      Pattern p = matcher.pattern();
      System.out.println("Pattern used to match the given date: 
"+p);
   }
}

출력 결과

Enter your date of birth
01/21/2019
Date is valid
Pattern used to match the given date:
^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}

예제2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternExample {
   public static void main(String args[]) {
      //사용자로부터 문자열을 읽어들이기
      System.out.println("문자열을 입력하세요");
      Scanner sc = new Scanner(System.in);
      String input = sc.next();
      //숫자로 시작하는 단어와 일치하는 정규 표현식
      String regex = "^[0-9].*$";
      //정규 표현식 컴파일
      Pattern pattern = Pattern.compile(regex);
      //매칭 메이커 객체 검색
      Matcher matcher = pattern.matcher(input);
      Pattern p = matcher.pattern();
      System.out.println("Pattern을 사용하여 주어진 입력 문자열을 일치시키기 위한 패턴: ");+p);
      //일치 여부 확인
      if(matcher.matches())
         System.out.println("첫 번째 문자는 숫자입니다");
      else
         System.out.println("첫 번째 문자는 숫자가 아닙니다");
   }
}

출력 결과

문자열을 입력하세요
2sample
Pattern을 사용하여 주어진 입력 문자열을 일치시키기 위한 패턴: ^[0-9].*$
첫 번째 문자는 숫자입니다