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

Regular Expression (Regex) ใน C# พร้อมตัวอย่าง

Regular Expression (Regex) คือ Pattern สำหรับ Match/Search/Replace ข้อความ .NET มี Regex Engine ใน System.Text.RegularExpressions

คลาสหลัก

  • Regex — Static/Instance Methods สำหรับ Match, Replace, Split
  • Match — ผลลัพธ์การ Match ครั้งเดียว
  • MatchCollection — หลาย Match
  • Group / Capture — กลุ่มย่อยใน Pattern

ตัวอย่าง 1: Split String ด้วย Regex.Split

using System;
using System.Text.RegularExpressions;

class Demo {
    static void Main() {
        string str = "Hello\r\nWorld\r\nLine3";
        string[] lines = Regex.Split(str, @"\r\n|\r|\n"); // Handle ทุก Line Ending
        
        foreach (string line in lines) {
            Console.WriteLine($"[{line}]");
        }
    }
}

ตัวอย่าง 2: ลบ Whitespace ซ้ำ (Normalize Whitespace)

string input = "Hello    World\t\tTest";
string pattern = @"\s+";        // หนึ่งหรือหลาย Whitespace
string replacement = " ";       // แทนที่ด้วย Space เดียว

Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
// ผลลัพธ์: "Hello World Test"

// หรือ One-liner
string result2 = Regex.Replace(input, @"\s+", " ");

ตัวอย่าง 3: Validate Email (Basic)

string emailPattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$";
bool isValid = Regex.IsMatch("user@example.com", emailPattern); // True
bool isValid2 = Regex.IsMatch("invalid", emailPattern); // False

ตัวอย่าง 4: Extract Numbers จาก String

string text = "Order 123: 5 items at $29.99 each";
var numbers = Regex.Matches(text, @"\d+(\.\d+)?");
foreach (Match m in numbers) {
    Console.WriteLine(m.Value); // 123, 5, 29.99
}

ตัวอย่าง 5: Named Groups (C# 7+)

string pattern = @"(?\d{4})-(?\d{2})-(?\d{2})";
Match match = Regex.Match("2024-01-15", pattern);
if (match.Success) {
    Console.WriteLine($"Year: {match.Groups["year"].Value}");  // 2024
    Console.WriteLine($"Month: {match.Groups["month"].Value}"); // 01
    Console.WriteLine($"Day: {match.Groups["day"].Value}");    // 15
}

Regex Options

Optionคำอธิบาย
IgnoreCaseCase-insensitive matching
Multiline^ $ Match ทุกบรรทัด
Singleline. Match Newline ด้วย
CompiledCompile เป็น Assembly (เร็วกว่าเมื่อใช้ซ้ำ)
ExplicitCaptureCapture เฉพาะ Named Groups

Performance Tips

  • ใช้ RegexOptions.Compiled สำหรับ Pattern ที่ใช้ซ้ำบ่อย
  • Cache Regex Instance (Static Readonly) — ไม่ต้อง `new Regex()` ทุกครั้ง
  • หลีกเลี่ยง Catastrophic Backtracking: ใช้ Possessive Quantifiers หรือ Atomic Groups
  • Prefer String.Split / Contains / StartsWith สำหรับงานง่าย — เร็วกว่า Regex มาก

ตัวอย่างครบถ้วน: Compiled Regex Cache

using System;
using System.Text.RegularExpressions;

class LogParser {
    // Static Compiled Regex — สร้างครั้งเดียว ใช้ตลอดชีวิต Process
    private static readonly Regex _timestampRegex = new Regex(
        @"(?