开发者

Regexp for web site url validation

开发者 https://www.devze.com 2023-03-20 02:49 出处:网络
How to validate by regular expression these urls: http://123.12.12.124:1234/default.html http://www.mysite.com

How to validate by regular expression these urls:

http://123.12.12.124:1234/default.html
http://www.mysite.com
http://www.mysite.com/
https://www.mysite.com
anyProtocol://www.mysite.com
www.mysite.com
mysite.com

and

http://www.my.site.com/default.aspx
http://www.my.site.com/default
http://www.my.site.com/default/
anyProtocol://www.my.site.com/default.anyExtension

开发者_StackOverflow社区and

http://www.my.site.com
anyProtocol://www.my.site.com/
https://www.my.site.com
www.my.site.com
my.site.com


Rather than trying to validate the URL yourself, have a look at the System.Uri class. If you try creating a Uri with an invalid address it should throw a UriFormatException. Quick example:

var valid = false;
try { 
    new Uri(someUrl);
    valid = true;
}
catch (UriFormatException) {}

This will be invalid if the scheme (http:// part) isn't included though as it isn't a valid URI, so you should try to make the input URL sane first.


If you are trying to build your own url rewrit engine in .NET then I would strongly recommend that you use the already existing products. Linke the built-in in IIS 7.

But otherwise, here a little hint on what you actuelly need to check for:

http://123.12.12.124:1234/default.html

I would simply check that its an exakt match.

http://www.mysite.com http://www.mysite.com/ https://www.mysite.com anyProtocol://www.mysite.com www.mysite.com mysite.com

Since you say anyprotocol and even just mysite.com then i would check that mysite.com is in the url and that it dosnt have more then at most a "/" after the url.

http://www.my.site.com/default.aspx http://www.my.site.com/default http://www.my.site.com/default/ anyProtocol://www.my.site.com/default.anyExtension

http://www.my.site.com anyProtocol://www.my.site.com/ https://www.my.site.com www.my.site.com my.site.com

Here you only need to check that the url contains my "my.site.com" and also add a (0,1) occurence of "default" since you dont rely care about the extension.

0

精彩评论

暂无评论...
验证码 换一张
取 消