【问题标题】:Remove subdomains from URI从 URI 中删除子域
【发布时间】:2014-10-20 09:04:48
【问题描述】:

我想从 URI 中删除子域名。

示例: 我想从 Uri“subdomain.sub2.baseurl.com”返回“baseurl.com”。

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

谢谢。

【问题讨论】:

  • 从技术上讲,您示例中的“顶级”是 .com,顶级是 .com 的子域,因此您要提取的域的子集几乎是任意的。跨度>
  • 感谢您的 cmets。因此,我认为 Regex 是去这里的唯一方法?
  • 我认为正则表达式可能是你最好的选择。
  • 谢谢 Ben,我已经用正确的术语更新了我的问题。

标签: c# windows-phone-8 uri


【解决方案1】:

这应该可以完成:

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

【讨论】:

  • @holex 这不是 OP 提出的问题的重点。但是这个代码可以很容易地修改来做到这一点。
  • 我实际上指的是您的代码根本没有正确删除子域 - 因此您的代码不正确。
  • @holex。放假回家后会测试调整。
  • 刚刚测试过,完全符合 OP 要求。从这里可以看出,rextester.com/ABMY57739。现在请不要管它。
  • 确定。我会在这里留下不正确的答案。 -1,当然,直到你修复它并且算法正确识别 subdomain.domain.co.uk 地址并显示以下正确输入,如 domian.co.uk,而不仅仅是 co.uk——在这种情况下绝对不正确。跨度>
猜你喜欢
  • 1970-01-01
  • 2011-07-16
  • 2012-06-02
  • 2011-04-24
  • 2015-08-20
  • 2017-09-20
  • 2016-01-16
  • 1970-01-01
  • 2018-03-10
相关资源
最近更新 更多