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


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

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

更新于: 2020 年 6 月 22 日

2K+ 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.