Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lớp Regex và các phương thức trong C#

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ứcMô tảTrả về
IsMatch(input)Kiểm tra có khớp khôngbool
IsMatch(input, startat)Kiểm tra từ vị trí startatbool
IsMatch(input, pattern)Static: kiểm tra pattern trên inputbool
Match(input)Tìm khớp đầu tiênMatch
Matches(input)Tìm tất cả khớpMatchCollection
Replace(input, replacement)Thay thế tất cả khớpstring
Replace(input, replacer)Thay thế bằng delegate/funcstring
Split(input)Tách chuỗi theo patternstring[]

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, \DChữ số / Không phải chữ số
\w, \WWord char (a-z, A-Z, 0-9, _) / Không phải
\s, \SWhitespace / 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+).