การใช้ 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*
| สัญลักษณ์ | ความหมาย |
\b | Word boundary (ขอบเขตคำ - เริ่มต้นหรือจบคำ) |
M | ตัวอักษร M ตรงตัว |
\w* | ตัวอักษร/ตัวเลข/ขีดล่าง 0 ตัวขึ้นไป |
Pattern พื้นฐานที่ใช้บ่อย
| Pattern | ความหมาย | ตัวอย่างจับคู่ |
\d | ตัวเลข 0-9 | 123 |
\d+ | ตัวเลข 1 ตัวขึ้นไป | 45, 100 |
\w | ตัวอักษร ตัวเลข _ | a, Z, 9, _ |
\s | Whitespace (space, tab, newline) | |
. | ตัวอักษรใดๆ ยกเว้น newline | a, 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