string sURL = "http://subdomain.website.com/index.htm";
MessageBox.Show(new System.Uri(sURL).Host);
给我 “subdomain.website.com”
但我需要任何的主域名 “website.com”网址或网页链接。
我该怎么做?
string sURL = "http://subdomain.website.com/index.htm";
MessageBox.Show(new System.Uri(sURL).Host);
给我 “subdomain.website.com”
但我需要任何的主域名 “website.com”网址或网页链接。
我该怎么做?
你可以做到这一点得到公正的主机名的最后两段:
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
。这不是最好的方法,但至少可以让您免于构建一个巨大的顶级域名列表。
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);
}
最好将正则表达式作为外语处理(给读者)并解释为什么你的模式能够解决这个问题。 – 2013-05-10 02:00:14
如果它是.org怎么办? – as9876 2015-11-08 20:06:38
你可以试试这个。如果您在数组中定义它,它可以处理多种根域。
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);
}
}
@ p.s.w.g您说得对,改为使用EndsWith。 – 2power10 2013-05-10 07:45:33
+1这是一个很好的解决方案。 – 2013-05-10 07:49:35
到http://stackoverflow.com/questions/4643227/top-level-domain-from-url-in-c-sharp – ysrb 2013-05-10 01:35:17
类似其实你想要的顶级域名。 subdomain.website.com是域名,website.com是顶级域名。 – ysrb 2013-05-10 01:35:54
这真的不是一个很难解析的字符串。你是否尝试过'.Split'和'string.Join'的简单组合? – 2013-05-10 01:48:54