从 foo.bar.car.com 中的 URL 获取特定子域 [英] Get specific subdomain from URL in foo.bar.car.com

查看:24
本文介绍了从 foo.bar.car.com 中的 URL 获取特定子域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 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.我应该使用 split 并取 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; 
}

这篇关于从 foo.bar.car.com 中的 URL 获取特定子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆