从URI中删除子域

本文关键字:删除 URI | 更新日期: 2023-09-27 18:27:03

我想从URI中删除子域名称。

示例:我想从Uri"sub2.baseurl.com子域"返回'baseurl.com'。

有没有一种使用URI类实现这一点的方法,或者Regex是唯一的解决方案?

谢谢。

从URI中删除子域

这应该可以完成:

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;
}