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

Posix Character Class \p{Punct} ใน Java Regex

Character class \p{Punct} ใช้ match punctuation marks (เครื่องหมายวรรคตอน) ตาม POSIX definition ประกอบด้วย:

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

รวมสัญลักษณ์พิเศษทั้งหมดที่ไม่ใช่ alphanumeric และไม่ใช่ whitespace

ตัวอย่างที่ 1: นับจำนวน punctuation marks

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AlphanumericExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string:");
        String input = sc.nextLine();

        String regex = "\\p{Punct}";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        int count = 0;
        while (matcher.find()) {
            count++;
        }
        System.out.println("Number of punctuation marks: " + count);
    }
}

Output 1

Enter a string
Hello, how are you. Welcome to Tutorialspoint.
Number of punctuation marks: 3

คำอธิบาย: , (comma), . (period), . (period) = 3 punctuation marks

ตัวอย่างที่ 2: หาสตริงที่ประกอบด้วย punctuation เท่านั้น

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main(String[] args) {
        // Regex: เริ่มจบด้วย punctuation เท่านั้น
        String regex = "^\\p{Punct}+$";

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter 5 input strings:");
        String[] input = new String[5];
        for (int i = 0; i < 5; i++) {
            input[i] = sc.nextLine();
        }

        Pattern p = Pattern.compile(regex);
        System.out.println("Strings with only punctuation characters:");
        for (int i = 0; i < 5; i++) {
            Matcher m = p.matcher(input[i]);
            if (m.matches()) {
                System.out.println(m.group());
            }
        }
    }
}

Output

Enter 5 input strings:
hello
1234
123text.!!
!!!!!
..!!,,
Strings with only punctuation characters:
!!!!!
..!!,,

ความแตกต่าง \p{Punct} vs อื่นๆ

Class Match ไม่ Match
\p{Punct} !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ a-z, A-Z, 0-9, space, \t, \n
\p{Graph} Alnum + Punct space, control chars
\p{Print} Graph + Space control chars
\p{Alnum} Alpha + Numeric Punct, space

กรณีใช้งานทั่วไป

  • Validate password: ต้องมี special characters อย่างน้อย 1 ตัว: .*\\p{Punct}.*
  • Split text ด้วย punctuation: str.split("\\p{Punct}+")
  • Remove punctuation: str.replaceAll("\\p{Punct}", "")
  • Count punctuation density ใน text analysis
  • Detect SQL injection patterns (quotes, semicolons, comments)

หมายเหตุเกี่ยวกับ Unicode

ใน Java \p{Punct} รองรับ Unicode punctuation categories (Pd, Ps, Pe, Pi, Pf, Po, Pc) ด้วย ไม่ใช่แค่ ASCII เท่านั้น ตัวอย่าง: 「」、『』、《》、‹›、«» เป็นต้น