从 URI 中删除子域 [英] Remove subdomains from URI

查看:30
本文介绍了从 URI 中删除子域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 URI 中删除子域名.

I want to remove subdomain names from a URI.

示例:我想从 Uri "subdomain.sub2.baseurl.com" 返回 'baseurl.com'.

Example: I want to return 'baseurl.com' from the Uri "subdomain.sub2.baseurl.com".

有没有办法使用 URI 类来做到这一点,或者 Regex 是唯一的解决方案?

Is there a way of doing this using URI class or is Regex the only solution?

谢谢.

推荐答案

这应该可以搞定:

var tlds = new List<string>()
{
    //the second- and third-level TLDs you expect go here, set to null if working with single-level TLDs only
    "co.uk"
};

Uri request = new Uri("http://subdomain.domain.co.uk");
string host = request.Host;
string hostWithoutPrefix = null;

if (tlds != null)
{
    foreach (var tld in tlds)
    {
        Regex regex = new Regex($"(?<=\\.|)\\w+\\.{tld}$");
        Match match = regex.Match(host);


        if (match.Success)
            hostWithoutPrefix = match.Groups[0].Value;
    }
}

//second/third levels not provided or not found -- try single-level
if (string.IsNullOrWhiteSpace(hostWithoutPrefix))
{
    Regex regex = new Regex("(?<=\\.|)\\w+\\.\\w+$");
    Match match = regex.Match(host);


    if (match.Success)
        hostWithoutPrefix = match.Groups[0].Value;
}

这篇关于从 URI 中删除子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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