Remove subdomains from URI

风流意气都作罢 提交于 2019-12-24 14:34:14

问题


I want to remove subdomain names from a URI.

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

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

Thank you.


回答1:


This should get it done:

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


来源:https://stackoverflow.com/questions/26461963/remove-subdomains-from-uri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!