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

การจับคู่รูปแบบ (Pattern Matching) ใน C# ด้วย Regex

การใช้ Regular Expressions (Regex) ใน C#

Regular Expression (Regex) เป็นรูปแบบ (pattern) ใช้สำหรับค้นหา จับคู่ และจัดการข้อความ ใช้ namespace System.Text.RegularExpressions

ตัวอย่าง: หาคำที่ขึ้นต้นด้วย 'M'

using System;
using System.Text.RegularExpressions;

namespace Demo
{
    class Program
    {
        private 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}' ที่ตำแหน่ง {m.Index}");
            }
        }

        static void Main(string[] args)
        {
            string str = "Mandatory requirements for a Cricket Match Event!";
            Console.WriteLine("คำที่ขึ้นต้นด้วย 'M':");
            ShowMatch(str, @"\bM\w*");
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

คำที่ขึ้นต้นด้วย 'M':
Pattern: \bM\w*
พบ: 'Mandatory' ที่ตำแหน่ง 0
พบ: 'Match' ที่ตำแหน่ง 28

อธิบาย Pattern: \bM\w*

สัญลักษณ์ความหมาย
\bWord boundary (ขอบเขตคำ - เริ่มต้นหรือจบคำ)
Mตัวอักษร M ตรงตัว
\w*ตัวอักษร/ตัวเลข/ขีดล่าง 0 ตัวขึ้นไป

Pattern พื้นฐานที่ใช้บ่อย

Patternความหมายตัวอย่างจับคู่
\dตัวเลข 0-9123
\d+ตัวเลข 1 ตัวขึ้นไป45, 100
\wตัวอักษร ตัวเลข _a, Z, 9, _
\sWhitespace (space, tab, newline)
.ตัวอักษรใดๆ ยกเว้น newlinea, 1, @
^เริ่มต้นสตริง/บรรทัด^Hello
$จบสตริง/บรรทัดWorld$
[abc]ตัวอักษรใดตัวหนึ่งในชุดa, b, c
[a-z]ช่วงตัวอักษรa ถึง z

เมธอด Regex ที่ใช้บ่อย


// ตรวจสอบว่าตรงกันหรือไม่ (bool)
bool isMatch = Regex.IsMatch(input, pattern);

// หาครั้งแรกที่ตรง
Match match = Regex.Match(input, pattern);

// หาทั้งหมดที่ตรง
MatchCollection matches = Regex.Matches(input, pattern);

// แทนที่ข้อความ
string result = Regex.Replace(input, pattern, replacement);

// แยกสตริงด้วย pattern
string[] parts = Regex.Split(input, pattern);

ตัวอย่างเพิ่มเติม: Validate Email


string emailPattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$";
Console.WriteLine(Regex.IsMatch("test@example.com", emailPattern)); // True
Console.WriteLine(Regex.IsMatch("invalid-email", emailPattern));    // False