简体   繁体   English

在C#中选择带有正则表达式的主机名?

[英]Select a HostName with Regex in C#?

There are some addresses as follows : 地址如下:

http://rs320tl.rapidshare.com/files/119371167/sth.rar

I'm gonna select rs320tl.rapidshare.com with Regex, but I'm not familiar with Regular Expressions. 我要使用Regex选择rs320tl.rapidshare.com ,但我对正则表达式不熟悉。
Would you please guide me ? 你能指导我吗?

Thanks. 谢谢。

PS. PS。
rs320tl in the address is variable. 地址中的rs320tl是可变的。

You should not use regular expressions to do this. 您不应使用正则表达式来执行此操作。

Instead, use the Uri class: 而是使用Uri类:

Uri uri = new Uri(yourString, UriKind.Absolute);
string host = uri.Host;

If you want to check whether the string is acutally a URL, use the following code: 如果要检查字符串是否是URL,请使用以下代码:

Uri uri;
if (!Uri.TryCreate(yourString, UriKind.Absolute, out uri))
    //String is not a valid URL.  Waah waah waah
string host = uri.Host;

If you really want to go down the Regex/C# route, I think what you are looking for is something like this: 如果您真的想沿着Regex / C#路线走,我想您正在寻找的是这样的东西:

string sOriginalUrl = "http://rs320tl.rapidshare.com/files/119371167/sth.rar";
string sPattern = "http://(?'host'[0-9a-zA-Z-.]*)/.*";
Regex re = new Regex(sPattern, RegexOptions.ExplicitCapture);
string sHost = re.Match(sOriginalUrl).Groups["host"].Value;

“ //(\\w.*?\\w)/”组[1]将包含您的网址

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM