Regular Expression (Regex) คือสตริงตัวอักษรกำหนด Pattern ใช้ค้นหา/แทนที่ข้อความ
Java มี java.util.regex package ประกอบ 3 คลาส:
- Pattern - Compiled regex, มี
compile(),matcher() - Matcher - Match Engine, มี
find(),group(),start(),replaceAll() - 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))
| Flag | Constant | คำอธิบาย |
|---|---|---|
i | Pattern.CASE_INSENSITIVE | Case insensitive matching |
m | Pattern.MULTILINE | ^ และ $ match ทุกบรรทัด |
s | Pattern.DOTALL | . match newline ด้วย |
u | Pattern.UNICODE_CHARACTER_CLASS | Unicode properties |
x | Pattern.COMMENTS | Whitespace และ 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"