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

Tìm chuỗi con khớp Regex trong C#

Dùng System.Text.RegularExpressions.Regex để tìm substring khớp pattern. Match (đầu tiên), Matches (tất cả).

Ví dụ cơ bản

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string text = "My make is make and make";
        string pattern = @"\bmake\b"; // Word boundary - từ "make" nguyên vẹn
        
        Console.WriteLine($"Text: {text}");
        Console.WriteLine($"Pattern: {pattern}");
        
        // Match đầu tiên
        Match match = Regex.Match(text, pattern);
        if (match.Success)
            Console.WriteLine($"First match: '{match.Value}' at index {match.Index}");
        
        // Tất cả matches
        Console.WriteLine("\nAll matches:");
        MatchCollection matches = Regex.Matches(text, pattern);
        foreach (Match m in matches)
        {
            Console.WriteLine($"  '{m.Value}' at index {m.Index}, length {m.Length}");
        }
        
        // Replace
        string replaced = Regex.Replace(text, pattern, "model");
        Console.WriteLine($"\nReplaced: {replaced}");
    }
}

Kết quả đầu ra

Text: My make is make and make
Pattern: \bmake\b
First match: 'make' at index 3
All matches:
  'make' at index 3, length 4
  'make' at index 11, length 4
  'make' at index 19, length 4

Replaced: My model is model and model

Common Regex Patterns

PatternÝ nghĩa
\dChữ số [0-9]
\wWord char [a-zA-Z0-9_]
\sWhitespace
\bWord boundary
^ / $Start/End string
.*Bất kỳ ký tự nào (trừ newline)
(...)Capture group

Ví dụ thực tế: Tách email, phone

string text = "Contact: john@example.com or 090-123-4567";

var emails = Regex.Matches(text, @"\b[\w.+-]+@[\w-]+\.[\w.]+\b");
var phones = Regex.Matches(text, @"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b");

foreach (Match m in emails) Console.WriteLine($"Email: {m.Value}");
foreach (Match m in phones) Console.WriteLine($"Phone: {m.Value}");