剥离协议和子域从URL(Strip protocol and subdomain from a UR

2019-10-18 14:54发布

我使用下面的代码删除http://www.dev. 从网址:

Uri uri = new Uri(this.Referrer);
    if (uri != null )
        return uri.GetLeftPart(UriPartial.Authority).Replace("http://dev.", "").Replace("http://www.", "").Replace("http://", "");
    else
        return null;

我不喜欢说我依靠.Replace()函数。 我有一个bug相当长的一段时间,直到我意识到this.Referrer没有足够的子域。

有没有更优雅的方式来做到这一点?

Answer 1:

你可以尝试使用这样的正则表达式:

http:\/\/(.*?)[.?]|http:\/\/

而不是执行多个内容替换。 这会赶上你遇到任何其他子域。 我不知道的另一种方式,你可以做到这一点。

这实际上并不像短,因为它可能是,但我想保持它的可读性。



文章来源: Strip protocol and subdomain from a URL
标签: c# url