如何使用正則表示式在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP