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

Regular Expression ใน Java คืออะไร


Regular Expression (Regex) คือสตริงตัวอักษรกำหนด Pattern ใช้ค้นหา/แทนที่ข้อความ

Java มี java.util.regex package ประกอบ 3 คลาส:

  1. Pattern - Compiled regex, มี compile(), matcher()
  2. Matcher - Match Engine, มี find(), group(), start(), replaceAll()
  3. PatternSyntaxException - Unchecked exception สำหรับ regex syntax error

ตัวอย่างที่ 1: ลบ Non-ASCII Characters

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

public class Example {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input string: ");
        String input = sc.nextLine();
        
        // [^\\p{ASCII}] = ไม่ใช่ ASCII character
        String regex = "[^\\p{ASCII}]";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "");  // แทนที่ด้วย empty string
        }
        matcher.appendTail(sb);
        
        System.out.println("Result: \n" + sb.toString());
    }
}

Output

Enter input string: whÿ do we fall
Result: 
wh do we fall

ตัวอย่างที่ 2: หาตำแหน่งของตัวอักษร 't'

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

public class StartExample {
    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]";  // ตัวอักษร t
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        
        while (matcher.find()) {
            int start = matcher.start();
            System.out.println(start);
        }
    }
}

Output

Enter input text: Hello how are you welcome to Tutorialspoint
26
31
42

Regex Flags (Pattern.compile(regex, flags))

FlagConstantคำอธิบาย
iPattern.CASE_INSENSITIVECase insensitive matching
mPattern.MULTILINE^ และ $ match ทุกบรรทัด
sPattern.DOTALL. match newline ด้วย
uPattern.UNICODE_CHARACTER_CLASSUnicode properties
xPattern.COMMENTSWhitespace และ comments ใน pattern

ตัวอย่างใช้ Flags

// Case insensitive
Pattern pattern = Pattern.compile("java", Pattern.CASE_INSENSITIVE);
// หรือ
Pattern pattern = Pattern.compile("(?i)java");

// Multiline - ^ $ match ทุกบรรทัด
Pattern pattern = Pattern.compile("^start", Pattern.MULTILINE);

Performance Tips

  • Compile Pattern ครั้งเดียว ใช้ซ้ำ (Pattern เป็น immutable, thread-safe)
  • ใช้ matches() สำหรับ match ทั้งสตริง, find() สำหรับหาบางส่วน
  • หลีกเลี่ยง Catastrophic Backtracking (nested quantifiers เช่น (a+)+)
  • Prefer String.matches(regex) สำหรับ one-liner (แต่ compile ใหม่ทุกครั้ง)

String Convenience Methods

String s = "Hello World";
s.matches("Hello.*");        // true - match ทั้งสตริง
s.split("\\s+");             // ["Hello", "World"]
s.replaceAll("\\s+", "-");   // "Hello-World"
s.replaceFirst("\\s+", "-"); // "Hello-World"