Hamish Grubijan
Hamish Grubijan

Reputation: 10830

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:

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 sense. 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!

Upvotes: 3

Views: 604

Answers (2)

Oleks
Oleks

Reputation: 32343

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.

Upvotes: 1

SLaks
SLaks

Reputation: 887797

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!!!

Upvotes: 4

Related Questions