เปิดใช้งาน literal parsing ของ pattern ในโหมดนี้ ตัวอักษรทั้งหมดรวมถึง escape sequences และ meta-characters ไม่มีความหมายพิเศษ จะถูกจัดการเป็น literal characters
เช่น ปกติถ้าคุณค้นหา regular expression "^This" ในข้อความอินพุตที่กำหนด มันจะจับคู่บรรทัดที่เริ่มต้นด้วยคำ "This"
ตัวอย่าง
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LTERAL_Example {
public static void main(String[] args) {
String input = "This is the first line\n" + "This is the second line\n" + "^This is the third line";
// Regular expression to accept date in MM-DD-YYY format
String regex = "^This";
// สร้าง Pattern object
Pattern pattern = Pattern.compile(regex, Pattern.LITERAL);
// สร้าง Matcher object
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
^This Number of matches: 1
ใน literal mode metacharacter "^" ไม่มีความหมาย และ regular expression "^This" จับคู่คำที่แน่นอน
ตัวอย่างเพิ่มเติม
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LTERAL_Example {
public static void main(String[] args) {
String input = "This is the first line\n" + "This is the second line\n" + "^This is the third line";
// Regular expression to accept date in MM-DD-YYY format
String regex = "^This";
// สร้าง Pattern object
Pattern pattern = Pattern.compile(regex, Pattern.LITERAL);
System.out.println("Usually it is printed as: \n" + input);
// สร้าง Matcher object
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
Usually it is printed as: This is the first line This is the second line ^This is the third line ^This Number of matches: 1