Regular expression เป็นรูปแบบ (pattern) ที่จับคู่กับข้อความนำเข้า .NET Framework มี regex engine สำหรับการจับคู่ Pattern ประกอบด้วยตัวอักษร literal, operators, หรือ constructs
ตัวอย่าง: จับคู่คำที่ขึ้นต้นด้วย 'S'
using System;
using System.Text.RegularExpressions;
namespace Demo {
class Program {
private static void showMatch(string text, string expr) {
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc) {
Console.WriteLine(m);
}
}
static void Main(string[] args) {
string str = "Email Sent Today!";
Console.WriteLine("Matching words that start with 'S': ");
showMatch(str, @"\bS\S*");
Console.ReadKey();
}
}
}
ผลลัพธ์
Matching words that start with 'S': The Expression: \bS\S* Sent
เมธอดสำคัญของคลาส Regex
| No. | Method & Description |
|---|---|
| 1 | IsMatch(string input) - ตรวจสอบว่ามีการจับคู่หรือไม่ |
| 2 | IsMatch(string input, int start) - ตรวจสอบจากตำแหน่งเริ่มต้น |
| 3 | IsMatch(string input, string pattern) - static method ตรวจสอบ pattern |
| 4 | Matches(string input) - ค้นหาทุกการจับคู่ |
| 5 | Replace(string input, string replacement) - แทนที่ข้อความที่จับคู่ |
| 6 | Split(string input) - แยกสตริงด้วย pattern |