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

So khớp mẫu (Pattern matching) trong C# với Regex

Biểu thức chính quy (regular expression) là một mẫu có thể so khớp với văn bản đầu vào. Mẫu bao gồm một hoặc nhiều ký tự chữ, toán tử hoặc cấu trúc.

Ví dụ hiển thị các từ bắt đầu bằng chữ 'M' dùng Regex:

Ví dụ

using System;
using System.Text.RegularExpressions;

namespace Demo {
    class Program {
        private static void showMatch(string text, string expr) {
            Console.WriteLine("Biểu thức: " + expr);
            MatchCollection mc = Regex.Matches(text, expr);
            foreach (Match m in mc) {
                Console.WriteLine(m);
            }
        }
        static void Main(string[] args) {
            string str = "Mandatory requirements for a Cricket Match Event!";
            Console.WriteLine("Các từ bắt đầu bằng 'M': ");
            showMatch(str, @"\bM\S*");
            Console.ReadKey();
        }
    }
}

Kết quả

Các từ bắt đầu bằng 'M':
Biểu thức: \bM\S*
Mandatory
Match

Chuỗi gốc:

string str = "Mandatory requirements for a Cricket Match Event!";

Để lấy tất cả từ bắt đầu bằng 'M', dùng mẫu:

@"\bM\S*"