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

การใช้ Regular Expression ใน Java เพื่อ Pattern Matching


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 object
  • Pattern.matcher(CharSequence input) - สร้าง Matcher สำหรับ input

เมธอดหลักของ Matcher

  • find() - หา match ถัดไป คืน boolean
  • matches() - Match ทั้งสตริง คืน boolean
  • group() - ดึง substring ที่ match
  • start(), end() - ตำแหน่งเริ่ม/จบของ match
  • replaceAll(String replacement) - แทนที่ทุก match
  • replaceFirst(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ไม่ใช่ตัวเลข
\wWord char [a-zA-Z0-9_]
\Wไม่ใช่ word char
\sWhitespace
\SNon-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();