มีตัวอักษร non-printable 7 ตัวที่ใช้ทั่วไป แต่ละตัวมีการแทนค่า hexadecimal:
| ชื่อ | Escape | Hex |
|---|---|---|
| Bell | \a | 0x07 |
| Escape | \e | 0x1B |
| Form feed | \f | 0x0C |
| Line feed | \n | 0x0A |
| Carriage return | \r | 0x0D |
| Horizontal tab | \t | 0x09 |
| Vertical tab | \v | 0x0B |
ตัวอย่าง 1: นับ tab ด้วย \t
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "\\t";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Number of tab spaces: " + count);
}
}
ผลลัพธ์
sample text with tab spaces
Number of tab spaces in the given input text: 3
ตัวอย่าง 2: ใช้ Hex representation \x09
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "\\x09"; // hex สำหรับ tab
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Number of tab spaces: " + count);
}
}
ผลลัพธ์
Enter input text: sample data with tab spaces
Number of tab spaces in the given input text: 4
สรุป
- ใช้ escape sequence เช่น
\t,\n,\rได้โดยตรง - ใช้ hex
\xHHได้เช่นกัน (HH = 2 หลัก hex) - Java รองรับ
\uXXXXสำหรับ Unicode (4 หลัก hex) - Octal:
\000ถึง\377
ตัวอย่างอื่นๆ
\x0Aหรือ\n= Line feed\x0Dหรือ\r= Carriage return\x1Bหรือ\e= Escape