[C#] C#根据URL返回域名 →→→→→进入此内容的聊天室

来自 , 2019-11-29, 写在 C#, 查看 97 次.
URL http://www.code666.cn/view/2bf7e9e8
  1. /*
  2. ** Method 1 (using the build-in Uri-object)
  3. */
  4. public static string ExtractDomainNameFromURL_Method1(string Url)
  5. {
  6.     if (!Url.Contains("://"))
  7.         Url = "http://" + Url;
  8.  
  9.     return new Uri(Url).Host;
  10. }
  11.  
  12. /*
  13. ** Method 2 (using string modifiers)
  14. */
  15. public static string ExtractDomainNameFromURL_Method2(string Url)
  16. {
  17.     if (Url.Contains(@"://"))
  18.         Url = Url.Split(new string[] { "://" }, 2, StringSplitOptions.None)[1];
  19.  
  20.     return Url.Split('/')[0];
  21. }
  22.  
  23. /*
  24. ** Method 3 (using regular expressions -> slowest)
  25. */
  26. public static string ExtractDomainNameFromURL_Method3(string Url)
  27. {
  28.     return System.Text.RegularExpressions.Regex.Replace(
  29.         Url,
  30.         @"^([a-zA-Z]+:\/\/)?([^\/]+)\/.*?$",
  31.         "$2"
  32.     );
  33. }
  34.  
  35.  
  36.  
  37. //使用范例:
  38. // Some example urls:
  39. string[] Urls = new string[] {
  40.     "http://www.jonasjohn.de/snippets/csharp/",
  41.     "www.jonasjohn.de/snippets/csharp/",
  42.     "http://www.jonasjohn.de/",
  43.     "ftp://www.jonasjohn.de/",
  44.     "www.jonasjohn.de/",
  45.     "http://www.sharejs.com/codes/",
  46.     "https://subdomain.abc.def.jonasjohn.de/test.htm"
  47. };
  48.  
  49. // Test all urls with all different methods:
  50. foreach (string Url in Urls){
  51.     Console.WriteLine("Method 1: {0}", ExtractDomainNameFromURL_Method1(Url));
  52.     Console.WriteLine("Method 2: {0}", ExtractDomainNameFromURL_Method2(Url));
  53.     Console.WriteLine("Method 3: {0}", ExtractDomainNameFromURL_Method3(Url));
  54. }
  55. //csharp/2062

回复 "C#根据URL返回域名"

这儿你可以回复上面这条便签

captcha