Regular Expression (Regex) คือสตริงตัวอักษรที่กำหนดรูปแบบ (Pattern) ใช้ค้นหา/แทนที่ข้อความ
Java มีแพ็กเกจ java.util.regex สำหรับ Pattern Matching ประกอบด้วย:
- Pattern - Compiled representation ของ regex
- Matcher - Engine ที่ match pattern กับ input string
- PatternSyntaxException - Exception สำหรับ syntax error ใน regex
เมธอดหลักของ Pattern
Pattern.compile(String regex)- คอมไพล์ regex คืน Pattern objectPattern.matcher(CharSequence input)- สร้าง Matcher สำหรับ input
เมธอดหลักของ Matcher
find()- หา match ถัดไป คืน booleanmatches()- Match ทั้งสตริง คืน booleangroup()- ดึง substring ที่ matchstart(), end()- ตำแหน่งเริ่ม/จบของ matchreplaceAll(String replacement)- แทนที่ทุก matchreplaceFirst(String replacement)- แทนที่ match แรก
ตัวอย่าง: ตรวจสอบสตริงมีอักษรและตัวเลข
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) {
String regex = "[a-zA-Z][0-9]?"; // ตัวอักษรตามด้วยตัวเลข 0-1 ตัว
Scanner sc = new Scanner(System.in);
System.out.println("Enter an input string: ");
String input = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if (m.find()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
}
Output 1
Enter an input string: sample text Match occurred
Output 2
Enter an input string: sample text 34 56 Match occurred
Regex Pattern Cheat Sheet
| Pattern | ความหมาย |
|---|---|
. | ตัวอักษรใดๆ (ยกเว้น newline) |
\d | ตัวเลข [0-9] |
\D | ไม่ใช่ตัวเลข |
\w | Word char [a-zA-Z0-9_] |
\W | ไม่ใช่ word char |
\s | Whitespace |
\S | Non-whitespace |
^ | เริ่มสตริง |
$ | จบสตริง |
* | 0 หรือมากกว่า |
+ | 1 หรือมากกว่า |
? | 0 หรือ 1 |
{n} | พอดี n ครั้ง |
{n,} | n ครั้งขึ้นไป |
{n,m} | n ถึง m ครั้ง |
คอมไพล์ Pattern ซ้ำได้ (Performance)
// ดี - compile ครั้งเดียว ใช้ซ้ำ
Pattern emailPattern = Pattern.compile("^[\\w.+-]+@[\\w-]+\\.[\\w.-]+$");
Matcher m1 = emailPattern.matcher("a@b.com");
Matcher m2 = emailPattern.matcher("c@d.org");
// ไม่ดี - compile ทุกครั้ง
Pattern.compile(regex).matcher(input).matches();