Regular expression สำหรับ match date ในรูปแบบ dd-MM-yyyy (วัน-เดือน-ปี):
^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$
วิธี match date ใน string รูปแบบนี้:
- Compile regex ด้วย
Pattern.compile() - ได้ Matcher object จาก
pattern.matcher(input) - ใช้
matcher.matches()คืน true หาก match, false หากไม่
ตัวอย่าง 1
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 class รับ regex match กับ string ปัจจุบัน คืน true/false ใช้ validate date string ได้โดยตรง
ตัวอย่าง 2
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();
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");
}
}
}
Output 1
Enter your name: Janaki Enter your Date of birth: 26/09/1989 Given date of birth is not valid
Output 2
Enter your name: Janaki Enter your Date of birth: 09/26/1989 Given date of birth is valid
หมายเหตุ: Regex นี้เป็นรูปแบบ MM/dd/yyyy (เดือน/วัน/ปี) ไม่ใช่ dd-MM-yyyy ตามที่ระบุในหัวข้อ