Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- class DomainNameExtract
- {
- /*
- ** Method 1 (using the build-in Uri-object)
- */
- public static string ExtractDomainNameFromURL_Method1(string Url)
- {
- if (!Url.Contains("://"))
- Url = "http://" + Url;
- return new Uri(Url).Host;
- }
- /*
- ** Method 2 (using string modifiers)
- */
- public static string ExtractDomainNameFromURL_Method2(string Url)
- {
- if (Url.Contains(@"://"))
- Url = Url.Split(new string[] { "://" }, 2, StringSplitOptions.None)[1];
- return Url.Split('/')[0];
- }
- /*
- ** Method 3 (using regular expressions -> slowest)
- */
- public static string ExtractDomainNameFromURL_Method3(string Url)
- {
- return System.Text.RegularExpressions.Regex.Replace(
- Url,
- @"^([a-zA-Z]+:\/\/)?([^\/]+)\/.*?$",
- "$2"
- );
- }
- static void Main()
- {
- // Some example urls:
- string[] Urls = new string[]
- {
- "http://www.somedomain.bg/snippets/csharp/",
- "www.somedomain.bg/snippets/csharp/",
- "http://www.somedomain.bg/",
- "ftp://www.somedomain.bg/",
- "www.somedomain.bg/",
- "https://subdomain.abc.def.somedomain.bg/test.htm"
- };
- // Test all urls with all different methods:
- foreach (string Url in Urls)
- {
- Console.WriteLine("Method 1: {0}", ExtractDomainNameFromURL_Method1(Url));
- Console.WriteLine("Method 2: {0}", ExtractDomainNameFromURL_Method2(Url));
- Console.WriteLine("Method 3: {0}", ExtractDomainNameFromURL_Method3(Url));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement