Select a HostName with Regex in C#?
There are some addresses as follows :
http://r开发者_开发百科s320tl.rapidshare.com/files/119371167/sth.rar
I'm gonna select rs320tl.rapidshare.com
with Regex, but I'm not familiar with Regular Expressions.
Thanks.
PS.
rs320tl
in the address is variable.You should not use regular expressions to do this.
Instead, use the Uri class:
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:
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:
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)/" group[1] will have your url
精彩评论