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

โปรแกรม Java ตรวจสอบ Special Characters ใน String ด้วย Regex

ตัวอย่าง: ใช้ Pattern และ Matcher


import java.util.regex.*;

public class Demo {
    public static void main(String[] args) {
        String input = "This is a sample only !$@";
        
        // Pattern: ไม่ใช่ a-z, 0-9, space (case insensitive)
        Pattern pattern = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(input);
        
        boolean hasSpecial = matcher.find();
        
        if (hasSpecial) {
            System.out.println("Special character found in the string");
            // หาตำแหน่งและตัวอักษร
            matcher.reset();
            while (matcher.find()) {
                System.out.println("Found: '" + matcher.group() + "' at index " + matcher.start());
            }
        } else {
            System.out.println("No special characters found");
        }
    }
}

ผลลัพธ์

Special character found in the string
Found: '!' at index 21
Found: '$' at index 22
Found: '@' at index 23

Regex Pattern ความหมาย

  • [^a-z0-9 ] - Negated character class: ไม่ใช่ a-z, 0-9, space
  • Pattern.CASE_INSENSITIVE - ไม่สนใจพิมพ์เล็ก/ใหญ่ (ครอบคลุม A-Z ด้วย)
  • \\p{Punct} - Unicode punctuation characters (กว้างกว่า)
  • [\\p{Punct}&&[^._-]] - Punctuation ยกเว้น . _ -

ตัวอย่าง Pattern อื่นๆ


// เฉพาะสัญลักษณ์พิเศษทั่วไป
Pattern.compile("[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?]")

// รวม Unicode symbols
Pattern.compile("[\\p{So}\\p{Sm}\\p{Sk}]") // Symbol other, math, modifier

Performance Tip

Compile pattern หนึ่งครั้ง (static final) ไม่ควร compile ใน loop


private static final Pattern SPECIAL_CHAR_PATTERN = 
    Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);

public static boolean hasSpecialChar(String s) {
    return SPECIAL_CHAR_PATTERN.matcher(s).find();
}