如何剥离http://和www。使用c#输入的域名

时间:2012-12-20 09:44:08

标签: c# regex

在我正在处理的应用程序中,我们允许用户输入域名列表,我们希望用户以下列格式输入域名

但是当将这些域名存回我们的数据库时,我们只想以下列格式存储域名

格式:stackoverflow.com

所以想知道我是否有一个现成的助手可以用来完成这项工作,或者是否有任何建议以有效的方式做到这一点。

What have I tried ?

这就是我想出来的,

public static string CleanDomainName(string domain)
{
    domain = domain.Trim();
    if (domain.Split('.').Count() > 2)
    {
        domain = domain.Split('.')[1] + "." + domain.Split('.')[2];
    }
    return domain;
}

请帮我解决这个问题。

5 个答案:

答案 0 :(得分:5)

使用Regex替换字符串开头的表达式:

Regex.Replace(input, @"^(?:http(?:s)?://)?(?:www(?:[0-9]+)?\.)?", string.Empty, RegexOptions.IgnoreCase);

这将取代:

  • 最初的“http://”(或“https://”)后跟
  • 最终的“www。” (也有以下数字即:www8或www23)

答案 1 :(得分:2)

使用Uri类。

string url = "http://www.testsite.com/path/file.html";
Uri uri = new Uri(url);

有各种properties可以检索网址的不同部分。

使用uri.Host获取网址的www.testsite.com部分。一点点字符串操作可以删除www.;

string domain = uri.Host;
if (domain.StartsWith("www."))
{
    domain = domain.Substring(4);
}

答案 2 :(得分:1)

使用System.Uri类。

 System.Uri uri = new Uri("http://stackoverflow.com/search?q=something");
 string uriWithoutScheme = uri.Host.Replace("www.","") + uri.PathAndQuery;

这将为您提供:stackoverflow.com/search?q=something

答案 3 :(得分:-1)

public static string CleanDomainName(string url)
{
    var uri = url.Contains("http://") ? new Uri(url) : new Uri("http://" + url);
    var parts = uri.Host.Split('.');
    return string.Join(".", parts.Skip(parts.Length - 2));
}

答案 4 :(得分:-2)

/// <summary>
/// Clears the sub domains from a URL.
/// </summary>
/// <param name="url">The URL.</param>
/// <returns>String for a URL without any subdomains</returns>
private static string ClearUrlSubDomains(Uri url)
{
    var host = url.Host.ToLowerInvariant();
    if (host.LastIndexOf('.') != host.IndexOf('.'))
    {
        host = host.Remove(0, host.IndexOf('.') + 1); // Strip out the subdomain (i.e. remove en-gb or www etc)
    }
    return host;
}

您可以从您的域中创建一个新的Uri,因此调用它将是:

ClearUrlSubDomains(new Uri(domain))

这不会解决像http://www.something.somethingelse.com这样的网址,但可以使用等效的while结构进行修改。