เมธอด compile() ของ Pattern class รับ 2 พารามิเตอร์:
- String regex pattern
- Integer flag (field ของ Pattern class)
Flag Pattern.LITERAL เปิดใช้งาน literal parsing ทำให้ regex metacharacters และ escape sequences ไม่มีความหมายพิเศษ ถูกมองว่าเป็น literal characters ทั้งหมด ดังนั้นถ้าต้องการ match metacharacters เป็นตัวอักษรธรรมดา ให้ส่ง flag นี้ไปกับ compile()
ตัวอย่าง
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
System.out.println("Enter input data: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "^[0-9]";
Pattern pattern = Pattern.compile(regex, Pattern.LITERAL);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
System.out.println(matcher.group());
}
System.out.println("Number of matches: " + count);
}
}
Output 1
Enter input data: 9848022338 Number of matches: 0
Output 2
Enter input data: ^[0-9] ^[0-9] Number of matches: 1
เมื่อใช้ Pattern.LITERAL regex "^[0-9]" จะ match ตรงตัวอักษร "^[0-9]" ไม่ใช่ pattern เริ่มต้นด้วยตัวเลข