如何在 C# 中使用正则表达式验证 URL?

programmingserver side programmingcsharp更新于 2025/7/11 5:52:17

要进行验证,您需要检查协议。

http
https

为此,您需要检查 .com、.in、.org 等。

为此,请使用以下正则表达式 −

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

以下是代码 −

示例

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();
      }
   }
}

输出

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

相关文章