คลาส Pattern ของแพ็กเกจ java.regex เป็น compiled representation ของ regular expression
เมธอด compile() ของคลาสนี้รับค่าสตริงที่แทน regular expression และคืนค่า object Pattern ต่อไปนี้คือ signature ของเมธอดนี้
static Pattern compile(String regex)
รูปแบบอื่นของเมธอดนี้รับค่าจำนวนเต็มที่แทน flags ต่อไปนี้คือ signature ของเมธอด compile ที่มีสองพารามิเตอร์
static Pattern compile(String regex, int flags)
คลาส Pattern มี fields ต่างๆ แต่ละอันแทน flag
| S.No | Field and Description |
|---|---|
| 1 | CANON_EQ จับคู่ตัวอักษรสองตัวก็ต่อเมื่อ canonically equal |
| 2 | CASE_INSENSITIVE จับคู่ตัวอักษรโดยไม่คำนึงถึง case |
| 3 | COMMENTS อนุญาต whitespace และ comments ใน pattern |
| 4 | DOTALL เปิดใช้งาน dotall mode ที่ . match ทุกตัวอักษรรวม line terminators |
| 5 | LITERAL เปิดใช้งาน literal parsing ทุก metacharacters และ escape sequences เป็น literal |
| 6 | MULTILINE เปิดใช้งาน multiline mode ทั้ง input sequence ถูกจัดการเป็นบรรทัดเดียว |
| 7 | UNICODE_CASE เปิดใช้งาน Unicode-aware case folding ใช้ร่วม CASE_INSENSITIVE |
| 8 | UNICODE_CHARACTER_CLASS เปิดใช้งาน Unicode version ของ predefined character classes และ POSIX character classes |
| 9 | UNIX_LINES Flag นี้เปิดใช้งาน Unix lines mode |
เมธอด flags() ของคลาสนี้คืนค่า flag ที่ใช้ใน pattern ปัจจุบัน
ตัวอย่าง
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class COMMENTES_Example {
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();
// Regular expression to accept date in MM-DD-YYY format
String regex = "^(1[0-2]|0[1-9])/ # For Month\n" + "(3[01]|[12][0-9]|0[1-9])/ # For Date\n" + "[0-9]{4}$ # For Year";
// สร้าง Pattern object
Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
// สร้าง Matcher object
Matcher matcher = pattern.matcher(dob);
boolean result = matcher.matches();
if (result) {
System.out.println("Given date of birth is valid");
} else {
System.out.println("Given date of birth is not valid");
}
System.out.println("Flag used: " + pattern.flags());
}
}
Output
Enter your name: Krishna Enter your Date of birth: 09/26/1989 Given date of birth is valid Flag used: 4