代码:
string sURL = "http://subdomain.website.com/index.htm";
MessageBox.Show(new System.Uri(sURL).Host);给了我"subdomain.website.com“
但我需要任何网址或网络链接的主域"website.com“。
我该怎么做?
发布于 2013-05-10 09:59:59
您可以这样做,以仅获取主机名的最后两个段:
string[] hostParts = new System.Uri(sURL).Host.Split('.');
string domain = String.Join(".", hostParts.Skip(Math.Max(0, hostParts.Length - 2)).Take(2));或者这样:
var host = new System.Uri(sURL).Host;
var domain = host.Substring(host.LastIndexOf('.', host.LastIndexOf('.') - 1) + 1);此方法将发现包括至少两个域名部分,但也将包括两个或更少字符的中间部分:
var host = new System.Uri(sURL).Host;
int index = host.LastIndexOf('.'), last = 3;
while (index > 0 && index >= last - 3)
{
last = index;
index = host.LastIndexOf('.', last - 1);
}
var domain = host.Substring(index + 1);这将处理localhost、example.com和example.co.uk等域。这不是最好的方法,但至少它使您不必构建一个庞大的顶级域列表。
发布于 2013-05-10 15:21:05
你可以试试这个。如果在数组中定义根域,它可以处理许多类型的根域。
string sURL = "http://subdomain.website.com/index.htm";
var host = new System.Uri(sURL).Host.ToLower();
string[] col = { ".com", ".cn", ".co.uk"/*all needed domain in lower case*/ };
foreach (string name in col)
{
if (host.EndsWith(name))
{
int idx = host.IndexOf(name);
int sec = host.Substring(0, idx - 1).LastIndexOf('.');
var rootDomain = host.Substring(sec + 1);
}
}发布于 2013-05-10 09:59:05
尝试正则表达式?
using System.Text.RegularExpressions;
string sURL = "http://subdomain.website.com/index.htm";
string sPattern = @"\w+.com";
// Instantiate the regular expression object.
Regex r = new Regex(sPattern, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(sUrl);
if (m.Success)
{
MessageBox.Show(m.Value);
}https://stackoverflow.com/questions/16473838
复制相似问题