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

Regex Class และเมธอดใน C#

Regex Class ใน C# (Regular Expressions)

System.Text.RegularExpressions.Regex ใช้สำหรับ Pattern Matching, Validation, Extraction, Replacement ของข้อความ

เมธอดสำคัญของ Regex

เมธอดคำอธิบาย
IsMatch(input)ตรวจสอบว่ามี Match หรือไม่ (bool)
IsMatch(input, startat)ตรวจสอบจากตำแหน่งเริ่มต้นที่กำหนด
IsMatch(input, pattern)Static method ตรวจสอบ Pattern กับ Input
Match(input)คืน Match แรกที่เจอ (Match Object)
Matches(input)คืน MatchCollection (ทุก Match)
Replace(input, replacement)แทนที่ Match ทั้งหมดด้วย Replacement String
Split(input)แบ่ง String ด้วย Pattern คืน String[]

ตัวอย่าง: Matches() หาคำขึ้นต้น m จบ e


using System;
using System.Text.RegularExpressions;

namespace RegExApplication
{
    class Program
    {
        static void ShowMatch(string text, string pattern)
        {
            Console.WriteLine($"Pattern: {pattern}");
            MatchCollection matches = Regex.Matches(text, pattern);
            foreach (Match m in matches)
                Console.WriteLine(m.Value);
        }
        
        static void Main(string[] args)
        {
            string str = "make maze and manage to measure it";
            ShowMatch(str, @"\bm\S*e\b"); // คำขึ้นต้น m จบ e
            Console.ReadKey();
        }
    }
}

ผลลัพธ์


Pattern: \bm\S*e\b
make
maze
manage
measure

Regex Patterns พื้นฐาน

Patternความหมาย
\dDigit (0-9)
\wWord Char (a-z, A-Z, 0-9, _)
\sWhitespace
.ตัวอักษรใดๆ (ยกเว้น Newline)
^เริ่มสตริง
$จบสตริง
\bWord Boundary
* + ? {n} {n,} {n,m}Quantifiers (ดูบท Quantifiers)

ตัวอย่าง Replace และ Split


string text = "Hello   World\tC#";
// แทนที่ Whitespace หลายตัวเป็น Space เดียว
string clean = Regex.Replace(text, @"\s+", " "); // "Hello World C#"

// แยกด้วย Comma หรือ Semicolon
string[] parts = Regex.Split("a,b;c,d", @"[,;]"); // ["a","b","c","d"]

Performance Tip

  • ใช้ RegexOptions.Compiled สำหรับ Pattern ที่ใช้บ่อย
  • Cache Regex Instance ไม่ต้อง new ทุกครั้ง
  • Prefer string.Contains, StartsWith สำหรับ Case เรียบง่าย