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

Tìm số trong chuỗi bằng Regex C#

Trích xuất số từ chuỗi: Regex.Match (số đầu tiên), Regex.Matches (tất cả), pattern \d+.

Ví dụ minh họa

using System;
using System.Text.RegularExpressions;
using System.Linq;

class Program
{
    static void Main()
    {
        string text = "Welcome! We are open 365 days in a year! Call 090-123-4567 or 024.3876.5432";
        
        Console.WriteLine($"Text: {text}");
        
        // 1. Tìm số đầu tiên
        Match match = Regex.Match(text, @"\d+");
        if (match.Success)
            Console.WriteLine($"Số đầu tiên: {match.Value} at index {match.Index}");
        
        // 2. Tìm TẤT CẢ số
        Console.WriteLine("\nTất cả số (\\d+):");
        MatchCollection matches = Regex.Matches(text, @"\d+");
        foreach (Match m in matches)
            Console.WriteLine($"  {m.Value} at index {m.Index}");
        
        // 3. Tìm số điện thoại (pattern phức tạp hơn)
        Console.WriteLine("\nSố điện thoại pattern:");
        var phoneMatches = Regex.Matches(text, @"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b");
        foreach (Match m in phoneMatches)
            Console.WriteLine($"  {m.Value}");
        
        // 4. LINQ từ Matches
        var allNumbers = Regex.Matches(text, @"\d+")
                             .Cast()
                             .Select(m => m.Value)
                             .ToList();
        Console.WriteLine($"\nDanh sách số: [{string.Join(", ", allNumbers)}]");
        
        // 5. Thay thế số bằng [NUMBER]
        string masked = Regex.Replace(text, @"\d+", "[NUMBER]");
        Console.WriteLine($"\nMasked: {masked}");
    }
}

Kết quả đầu ra

Text: Welcome! We are open 365 days in a year! Call 090-123-4567 or 024.3876.5432

Số đầu tiên: 365 at index 23

Tất cả số (\d+):
  365 at index 23
  090 at index 44
  123 at index 48
  4567 at index 52
  024 at index 60
  3876 at index 64
  5432 at index 69

Số điện thoại pattern:
  090-123-4567
  024.3876.5432

Danh sách số: [365, 090, 123, 4567, 024, 3876, 5432]

Masked: Welcome! We are open [NUMBER] days in a year! Call [NUMBER] or [NUMBER]

Pattern phổ biến: \d+ (1+ chữ số), \d{3} (chính xác 3), \d{1,3} (1-3), [\d,.]+ (số có dấu phẩy/chấm).