获得URL特定子在foo.bar.car.com [英] Get specific subdomain from URL in foo.bar.car.com
本文介绍了获得URL特定子在foo.bar.car.com的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个URL,如下所示:
Given a URL as follows:
foo.bar.car.com.au
我需要提取 foo.bar
。
我碰到下面的代码:
private static string GetSubDomain(Uri url)
{
if (url.HostNameType == UriHostNameType.Dns)
{
string host = url.Host;
if (host.Split('.').Length > 2)
{
int lastIndex = host.LastIndexOf(".");
int index = host.LastIndexOf(".", lastIndex - 1);
return host.Substring(0, index);
}
}
return null;
}
这让我像 foo.bar.car
。我想FOO.BAR。如果我只是用分裂,并采取0和1?
This gives me like foo.bar.car
. I want foo.bar. Should i just use split and take 0 and 1?
但后来有可能WWWW。
But then there is possible wwww.
有此?
推荐答案
由于您的要求(您想第一两个层次,不包括的www。)我一个简单的方法倒是接近它是这样的:
Given your requirement (you want the 1st two levels, not including 'www.') I'd approach it something like this:
private static string GetSubDomain(Uri url)
{
if (url.HostNameType == UriHostNameType.Dns)
{
string host = url.Host;
var nodes = host.Split('.');
int startNode = 0;
if(nodes[0] == "www") startNode = 1;
return string.Format("{0}.{1}", nodes[startNode], nodes[startNode + 1]);
}
return null;
}
这篇关于获得URL特定子在foo.bar.car.com的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文