Skip to main content
 首页 » 编程设计

c#之需要 C# 正则表达式进行 URL 验证

2024年01月16日38webabcd

如何通过单个正则表达式验证 url:

http://83.222.4.42:8880/listen.pls 
http://www.my_site.com/listen.pls 
http://www.my.site.com/listen.pls 

是真实的?

我看到我提出的问题不完全:(,对不起我的错误。想法是我想借助正则表达式有效 url 进行验证,让它成为外部 IP 地址或域名。这就是想法,其他可以考虑有效的网址:
http://93.122.34.342/ 
http://193.122.34.342/abc/1.html 
http://www.my_site.com/listen2.pls 
http://www.my.site.com/listen.php 

等等。

请您参考如下方法:

通向 hell 的道路是用字符串解析铺就的。

尤其是 URL 解析是许多被利用的安全问题的根源。不要这样做。

例如,你想要这个匹配吗?

     

Note the uppercase scheme section. Remember that some parts of a URL are case sensitive, and some are not. Then there's encoding rules. Etc.

Start by using System.Uri to parse the URLs you provide:

var uri = new Uri("http://83.222.4.42:8880/listen.pls"); 

然后你可以写这样的东西:
if (uri.Scheme == "http" && 
    uri.Host == "83.222.4.42" && 
    uri.AbsolutePath == "/listen.pls" 
    ) 
{ 
    // ... 
}