Regex.Matches() tìm tất cả các khớp (matches) của mẫu regex trong chuỗi đầu vào, trả về MatchCollection.
Ví dụ kiểm tra URL hợp lệ
using System;
using System.Text.RegularExpressions;
namespace Demo
{
class Program
{
private static void ShowMatch(string text, string expr)
{
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc)
Console.WriteLine(m);
}
static void Main(string[] args)
{
string str = "https://demo.com";
Console.WriteLine("Đang khớp URL...");
ShowMatch(str, @"^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?");
Console.ReadKey();
}
}
}
Kết quả đầu ra
Đang khớp URL... https://demo.com
Lưu ý về regex URL: Mẫu trong ví dụ đơn giản hóa. URL thực tế phức tạp hơn, nên dùng Uri.TryCreate() hoặc thư viện chuyên dụng.