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

Biểu thức chính quy (Regular Expressions) trong C#

Regular Expression (Regex) là mẫu (pattern) để so khớp với văn bản đầu vào. .NET cung cấp engine Regex trong namespace System.Text.RegularExpressions.

Pattern bao gồm: ký tự chữ (literals), toán tử, cấu trúc (constructs).

Ví dụ: Tìm từ bắt đầu bằng 'S'

using System;
using System.Text.RegularExpressions;

namespace Demo
{
    class Program
    {
        private static void ShowMatch(string text, string expr)
        {
            Console.WriteLine("Expression: " + expr);
            MatchCollection mc = Regex.Matches(text, expr);
            foreach (Match m in mc)
                Console.WriteLine(m);
        }
        
        static void Main(string[] args)
        {
            string str = "Email Sent Today!";
            Console.WriteLine("Matching words starting with 'S':");
            ShowMatch(str, @"\bS\S*");
            Console.ReadKey();
        }
    }
}

Kết quả

Matching words starting with 'S':
Expression: \bS\S*
Sent

Các phương thức chính của class Regex:

STTPhương thức & Mô tả
1IsMatch(input): Kiểm tra có khớp không (bool).
2IsMatch(input, start): Kiểm tra từ vị trí start.
3IsMatch(input, pattern): Static, kiểm tra pattern.
4Matches(input): Trả về MatchCollection tất cả match.
5Replace(input, replacement): Thay thế tất cả match.
6Split(input): Tách chuỗi theo pattern.

Pattern thường dùng: \d (số), \w (chữ/số/_), \s (whitespace), ^$ (đầu/cuối chuỗi), \b (ranh giới từ), () (group), [] (character class), *+? (quantifier).