0

Hey i'm curious as to how to parse out the host name in a URL using regular expressions in C#.

i have the following regex:

Regex regexUrl = new Regex("://(?<host>([a-z\\d][-a-z\\d]*[a-z\\d]\\.)*[a-z][-a-z\\d]+[a-z])");

but it throws an error when the URL does not contain a "http://", and it also does not parse out the "www." part of the url.

So how would i code a function that parses out the "hostname.com" from a URL, even if it does not contain a "http://". Thanks :)

4 Answers 4

4

I wouldn't use regular expressions.

  1. Convert 'http://' to '' (empty string) in your string - that basically removes http:// if it's there
  2. Split the string on / as an array
  3. The hostname is the element at index 0
Sign up to request clarification or add additional context in comments.

Comments

3

Why not do somethiing like this instead?

Uri uri;
if (!Uri.TryCreate(s, UriKind.Absolute, out uri)) {
    if (!Uri.TryCreate("http://" + s, UriKind.Absolute, out uri)) {
        throw new ArgumentException();
    }
}

return uri.Host;

It's more lines but it's probably cleaner than a regex and easier to read.

2 Comments

This doesn't work when supply "testServer:666" . Host of URI will be Unknown. You should correct your sample like the following
if (!Uri.TryCreate(uriStr, UriKind.Absolute, out uri) || uri.HostNameType==UriHostNameType.Unknown) { if (!Uri.TryCreate("http://" + uriStr, UriKind.Absolute, out uri) || uri.HostNameType == UriHostNameType.Unknown) { throw new ArgumentException(); } }
0

If you insist on using a regex this should do: ^([a-z]+://)?(?<host>[a-z\d][a-z\d-]*(\.[a-z\d][a-z\d-]*)*)[/$]

The trick is to have the last character match either a / or the terminator ($)

Comments

-1

[^\/\.\s]+\.[^\/\.\s]+\/ - the only problem is that it requires / after hostname

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.