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

Validate URL với Regular Expression trong C#

Sử dụng Regex (Regular Expression) để kiểm tra định dạng URL. Pattern cần kiểm tra: giao thức (http/https), domain, TLD (.com, .vn, .org...), và optional path/query.

Pattern cơ bản

^(http|https?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?$

Mã nguồn hoàn chỉnh

using System;
using System.Text.RegularExpressions;

namespace RegExApplication
{
    class Program
    {
        private static void ShowMatch(string text, string expr)
        {
            Console.WriteLine("The Expression: " + expr);
            MatchCollection mc = Regex.Matches(text, expr);
            foreach (Match m in mc)
                Console.WriteLine(m);
        }
        
        static void Main(string[] args)
        {
            string str = "https://example.com";
            Console.WriteLine("Matching URL...");
            showMatch(str, @"^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?");
            Console.ReadKey();
        }
    }
}

Kết quả

Matching URL...
The Expression: ^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?
https://example.com

Phân tích Pattern

PhầnRegexGiải thích
Protocol^(http|https?://)?https:// hoặc https:// (tùy chọn)
Subdomain([\w-]+\.)+Một hoặc nhiều subdomain (www., api., v.v.)
Domain + TLD[\w-]+[.com|.in|.org]+Tên miền + TLD (lưu ý: [...] là character class, không phải group)
Path/Query(\[\?%&=]*)?Query string tùy chọn (pattern này không chuẩn)

Cải tiến Pattern chuẩn hơn (RFC 3986简化)

// Pattern tốt hơn
string urlPattern = @"^https?://([\w-]+\.)+[\w-]+(:\d+)?(/[\w-./?%&=]*)?$";

// Hoặc dùng Uri class (khuyến khích)
bool IsValidUrl(string url)
{
    return Uri.TryCreate(url, UriKind.Absolute, out Uri result)
        && (result.Scheme == Uri.UriSchemeHttp || result.Scheme == Uri.UriSchemeHttps);
}

Khuyến nghị

  • Ưu tiên Uri.TryCreate - built-in, chuẩn RFC, xử lý encoding, IDN, IPv6.
  • Regex URL phức tạp, dễ sai, khó maintain.
  • Chỉ dùng Regex khi cần validate pattern cụ thể (ví dụ: chỉ cho phép domain .com.vn).