从 URL 中剥离协议和子域 [英] Strip protocol and subdomain from a URL

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

问题描述

我使用以下代码从 URL 中删除 http://www.dev.:

I use the following code to remove http:// and www. or dev. from a URL:

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() 函数.我有一个错误很长一段时间,直到我意识到 this.Referrer 没有子域.

I don't like that I'm relying on the .Replace() function. I had a bug for quite a while until I realized that the this.Referrer didn't have the subdomain.

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

Is there a more elegant way to do this?

推荐答案

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

You could try using a regex like this:

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

而不是执行多次替换.这将捕获您遇到的任何其他子域.我不知道您可以通过其他方式实现这一目标.

Instead of performing multiple replaces. This would catch any other sub-domains you encounter. I'm not aware of another way you can achieve this.

这实际上并没有想象的那么短,但我想让它保持可读性.

This is actually not as short as it could be but I wanted to keep it readable.

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

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