English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
dd와 함께-MM-yyyy 형식의 날짜 일치하는 정규 표현식.
^(1[0-2]|0[1-9]/(3[01]|[12][0-9]|0[1-9]/[0-9]{4$
이 형식으로 문자열의 날짜를 일치시킵니다.
컴파일compile()
Pattern 클래스의 위 표현식을 통해
필요한 입력 문자열을matcher()
Pattern 클래스의 메서드의 파라미터는 Matcher 객체를 얻습니다.
matches()
일치가 발생하면 Matcher 클래스의 메서드는 true를 반환하고, 일치하지 않으면 false를 반환합니다. 따라서 데이터를 검증하기 위해 이 메서드를 호출합니다.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatchingDate { public static void main(String[] args) { String date = "01/12/2019"; String regex = "^(1[0-2]|0[1-9]/(3[01]|[12][0-9]|0[1-9]/[0-9]{4$"; //패턴 객체를 생성합니다 Pattern pattern = Pattern.compile(regex); //문자열에서 이미 컴파일된 패턴을 일치시킵니다 Matcher matcher = pattern.matcher(date); boolean bool = matcher.matches(); if(bool) { System.out.println("Date is valid"); } else { System.out.println("Date is not valid"); } } }
출력 결과
Date is valid
matches()
String 클래스의 메서드는 정규 표현식을 받아 현재 문자열과 일치 여부를 확인하고, 일치하면 true, 일치하지 않으면 false를 반환합니다. 따라서 주어진 날짜(문자열 형식)가 필요한 형식인지 확인해야 합니다-
날짜 문자열을 가져옵니다.
matches()
위의 정규 표현식을 매개변수로 전달하여 메서드를 호출합니다.
import java.util.Scanner; public class Just { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String name = sc.nextLine(); System.out.println("Enter your Date of birth: "); String dob = sc.nextLine(); //정규 표현식은 MM-DD-YYY 형식으로 날짜 입력 String regex = "^(1[0-2]|0[1-9]/(3[01]|[12][0-9]|0[1-9]/[0-9]{4$"; boolean result = dob.matches(regex); if(result) { System.out.println("Given date of birth is valid"); } else { System.out.println("Given date of birth is not valid"); } } }
Enter your name: Janaki Enter your Date of birth: 26/09/1989 Given date of birth is not valid
Enter your name: Janaki Enter your Date of birth: 09/26/1989 Given date of birth is valid