问题描述
我使用以下代码从 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 中剥离协议和子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!