Regex (Regular Expression) là mẫu (pattern) để khớp, tìm kiếm, trích xuất, thay thế, tách chuỗi. Lớp System.Text.RegularExpressions.Regex cung cấp API mạnh mẽ.
Các phương thức tĩnh (Static) và instance quan trọng
| Phương thức | Mô tả | Trả về |
IsMatch(input) | Kiểm tra có khớp không | bool |
IsMatch(input, startat) | Kiểm tra từ vị trí startat | bool |
IsMatch(input, pattern) | Static: kiểm tra pattern trên input | bool |
Match(input) | Tìm khớp đầu tiên | Match |
Matches(input) | Tìm tất cả khớp | MatchCollection |
Replace(input, replacement) | Thay thế tất cả khớp | string |
Replace(input, replacer) | Thay thế bằng delegate/func | string |
Split(input) | Tách chuỗi theo pattern | string[] |
Ví dụ: Matches - Tìm từ bắt đầu 'm' kết thúc 'e'
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string text = "make maze and manage to measure it";
string pattern = @"\bm\w*e\b"; // \b word boundary, \w* từ ký tự word
Console.WriteLine($"Text: {text}");
Console.WriteLine($"Pattern: {pattern}");
Console.WriteLine("Matches:");
MatchCollection matches = Regex.Matches(text, pattern);
foreach (Match m in matches)
{
Console.WriteLine($" Found: '{m.Value}' at index {m.Index}, length {m.Length}");
}
// Replace ví dụ
string replaced = Regex.Replace(text, pattern, "[MATCHED]");
Console.WriteLine($"\nReplaced: {replaced}");
// Split ví dụ
string csv = "apple,banana;cherry|date";
string[] fruits = Regex.Split(csv, @"[,;|]");
Console.WriteLine($"\nSplit: {string.Join(" | ", fruits)}");
}
}
Kết quả
Text: make maze and manage to measure it
Pattern: \bm\w*e\b
Matches:
Found: 'make' at index 0, length 4
Found: 'maze' at index 5, length 4
Found: 'manage' at index 14, length 6
Found: 'measure' at index 25, length 7
Replaced: [MATCHED] [MATCHED] and [MATCHED] to [MATCHED] it
Split: apple | banana | cherry | date
Pattern thường dùng (Cheat Sheet)
| Pattern | Ý nghĩa |
. | Bất kỳ ký tự nào (trừ newline) |
\d, \D | Chữ số / Không phải chữ số |
\w, \W | Word char (a-z, A-Z, 0-9, _) / Không phải |
\s, \S | Whitespace / Không phải |
^, $ | Đầu / Cuối chuỗi (hoặc dòng với Multiline) |
*, +, ? | 0 hoặc nhiều / 1 hoặc nhiều / 0 hoặc 1 |
{n}, {n,}, {n,m} | Đúng n / Tối thiểu n / Từ n đến m lần |
(...) | Group (capture) |
(?:...) | Non-capturing group |
| | Hoặc (alternation) |
Best Practices
- Dùng
@\"pattern\" (verbatim string) để tránh escape backslash.
- Compile regex nếu dùng lặp lại:
new Regex(pattern, RegexOptions.Compiled).
- Dùng
RegexOptions.IgnoreCase, Multiline, Singleline khi cần.
- Tránh catastrophic backtracking: không lồng quantifier (
(a+)+), dùng atomic group (?>...).
- Prefer
Span<char> / Memory<char> cho high-perf (.NET 7+).