开发者

Yet another URL prefix regex question (to be used in C#)

I have seen many regular expressions for Url validation. In my case I want the Url to be simpler, so the regex should be tighter:

Valid Url prefixes look like:

  • http[s]://[www.]addressOrIp[.something]/PageName.aspx[?]

This describe a prefix. I will be appending ?x=a&y=b&z=c later. I just want to check if the web page is live before accessing it, but even before that I want to make sure that it is properly configured. I want to treat bad url and host is down conditions differently, although when in doubt, I'd rather give a host is down message, because that is an ultimate test anyway. Hopefully that makes sen开发者_StackOverflow社区se. I guess what I am trying to say - the regex does not need be too aggressive, I just want it to cover say 95% of the cases.

This is C# - centric, so Perl regex extensions are not helpful to me; let's stick to the lowest common denominator.

Thanks!


You should use the Uri class:

Uri uri;

if (!Uri.TryCreate(str, UriKind.Absolute, out uri))
    //Bad bad bad!!!
if (uri.Scheme != "http" && uri.Scheme != "https")
    //Bad bad bad!!!
if (uri.Host.IndexOf('.') <0)
    //Bad bad bad!!!


Use System.Uri instead.

Then you will be able to work with your URL parts such as Host, Scheme, PathAndQuery etc and check the necessary conditions.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜