Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีตรวจสอบ URL ด้วย Regular Expression ใน C#?

ใช้ Regex (ใน System.Text.RegularExpressions) ตรวจสอบรูปแบบ URL โดยตรวจสอบโปรโตคอล (http/https) และโดเมน (.com, .in, .org, ฯลฯ)

Regular Expression ตัวอย่าง

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

คำอธิบาย: ตรวจสอบ http/https optional, โดเมนย่อย, โดเมนหลัก, TLD (.com/.in/.org), Query string optional

ตัวอย่างโค้ด

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]+(\[\?%&=]*)?$");
        }
    }
}

ผลลัพธ์

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

หมายเหตุ: Regex นี้เป็นตัวอย่างพื้นฐาน URL จริงซับซ้อนกว่านี้ (มี Port, Path, Fragment, International Domain) ควรใช้ Uri.TryCreate หรือ Library เฉพาะทางสำหรับ Production