Regular Expression (Regex) là mẫu (pattern) để so khớp với văn bản đầu vào. .NET cung cấp engine Regex trong namespace System.Text.RegularExpressions.
Pattern bao gồm: ký tự chữ (literals), toán tử, cấu trúc (constructs).
Ví dụ: Tìm từ bắt đầu bằng 'S'
using System;
using System.Text.RegularExpressions;
namespace Demo
{
class Program
{
private static void ShowMatch(string text, string expr)
{
Console.WriteLine("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 starting with 'S':");
ShowMatch(str, @"\bS\S*");
Console.ReadKey();
}
}
}
Kết quả
Matching words starting with 'S':
Expression: \bS\S*
Sent
Các phương thức chính của class Regex:
| STT | Phương thức & Mô tả |
|---|---|
| 1 | IsMatch(input): Kiểm tra có khớp không (bool). |
| 2 | IsMatch(input, start): Kiểm tra từ vị trí start. |
| 3 | IsMatch(input, pattern): Static, kiểm tra pattern. |
| 4 | Matches(input): Trả về MatchCollection tất cả match. |
| 5 | Replace(input, replacement): Thay thế tất cả match. |
| 6 | Split(input): Tách chuỗi theo pattern. |
Pattern thường dùng: \d (số), \w (chữ/số/_), \s (whitespace), ^$ (đầu/cuối chuỗi), \b (ranh giới từ), () (group), [] (character class), *+? (quantifier).