เปิดใช้งานการแยกวิเคราะห์ตามตัวอักษรของรูปแบบ ในที่นี้ อักขระทั้งหมดรวมทั้ง Escape Sequence และ Meta-character ไม่ได้มีความหมายพิเศษใดๆ ที่ถือว่าเป็นอักขระตามตัวอักษร
ตัวอย่างเช่น โดยปกติ หากคุณค้นหานิพจน์ทั่วไป “^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";
//Creating a Pattern object
Pattern pattern = Pattern.compile(regex,Pattern.LITERAL);
//Creating a 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);
}
} ผลลัพธ์
^This Number of matches: 1
ในโหมดตัวอักษร อักขระเมตา "^" จะไม่มีความหมาย และนิพจน์ทั่วไป "^นี่" จะตรงกับคำที่ตรงกันทุกประการ
ตัวอย่าง
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";
//Creating a Pattern object
Pattern pattern = Pattern.compile(regex,Pattern.LITERAL);
System.out.println("Usually it is printed as: \n"+input);
//Creating a 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);
}
} ผลลัพธ์
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