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

Tách chuỗi bằng Regular Expression trong C#


Để tách chuỗi bằng biểu thức chính quy (regex), sử dụng Regex.Split từ namespace System.Text.RegularExpressions.

Ví dụ

using System;
using System.Text.RegularExpressions;

class Demo
{
    static void Main()
    {
        // Chuỗi có xuống dòng (CRLF)
        string str = "Hello\r\nWorld";
        
        // Tách theo \r\n
        string[] res = Regex.Split(str, @"\r\n");
        
        foreach (string word in res)
            Console.WriteLine(word);
    }
}

Kết quả

Hello
World

Các pattern phổ biến

PatternÝ nghĩa
\s+Một hoặc nhiều khoảng trắng
\d+Một hoặc nhiều chữ số
\w+Một hoặc nhiều ký tự từ (chữ, số, _)
[,.;]Dấu phẩy, chấm, chấm phẩy
\r\n|\r|\nDòng mới Windows/Mac/Linux

Ví dụ tách từ (word split)

string text = "Hello, world! This is a test.";
string[] words = Regex.Split(text, @"\W+"); // Tách theo non-word chars
// Kết quả: ["Hello", "world", "This", "is", "a", "test", ""]

Lưu ý

  • Dùng @ trước chuỗi pattern để tránh escape (verbatim string)
  • Regex.Split mạnh hơn string.Split cho pattern phức tạp
  • Hiệu suất kém hơn string.Split cho trường hợp đơn giản