Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

จับคู่ตัวอักษรที่พิมพ์ไม่ได้ (Nonprintable) ใน Java Regex

มีตัวอักษร non-printable 7 ตัวที่ใช้ทั่วไป แต่ละตัวมีการแทนค่า hexadecimal:

ชื่อEscapeHex
Bell\a0x07
Escape\e0x1B
Form feed\f0x0C
Line feed\n0x0A
Carriage return\r0x0D
Horizontal tab\t0x09
Vertical tab\v0x0B

ตัวอย่าง 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