Để 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|\n | Dò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.Splitmạnh hơnstring.Splitcho pattern phức tạp- Hiệu suất kém hơn
string.Splitcho trường hợp đơn giản