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

Biểu thức chính quy (Regular Expression) trong C# với ví dụ


Regular expression là pattern so khớp với văn bản đầu vào. .NET cung cấp engine regex.

Tách chuỗi bằng Regex.Split:

string str = "Hello\r\nWorld";
string[] res = Regex.Split(str, "\r\n");

Ví dụ tách chuỗi

using System;
using System.Text.RegularExpressions;
class Demo {
    static void Main() {
        string str = "Hello\r\nWorld";
        string[] res = Regex.Split(str, "\r\n");
        foreach (string word in res) Console.WriteLine(word);
    }
}

Ví dụ xóa khoảng trắng thừa:

Ví dụ

using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
    class Program {
        static void Main(string[] args) {
            string input = "Hello World ";
            string pattern = "\\s+";
            string replacement = " ";
            Regex rgx = new Regex(pattern);
            string result = rgx.Replace(input, replacement);
            Console.WriteLine("Chuỗi gốc: {0}", input);
            Console.WriteLine("Chuỗi sau replace: {0}", result);
            Console.ReadKey();
        }
    }
}