tags:

views:

148

answers:

3

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.
Would you please guide me ?

Thanks.

PS.
rs320tl in the address is variable.

+4  A: 

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;
SLaks
Thanks, but what about the Regex one, Would you please post a regular expression to do that.
Mohammad
`http://([a-zA-Z0-9.-]+)/`
SLaks
SLaks, your Regular Expressions is wrong, I've tried it.
Mohammad
Here's a (tested) working regex: `http://([a-zA-Z0-9.-]+)/.*`
SLaks
Are you sure! it selects whole of the address!
Mohammad
You need to use the capture group.
SLaks
+1  A: 

"//(\w.*?\w)/" group[1] will have your url

rerun
Are you sure about the expression! I wanted to test it, I receive this error `Unrecognized escape sequence` for `w`
Mohammad
You need to put an `@` before the string.
SLaks
+2  A: 

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;
Ken
Thanks, but it doesn't work with `rs320tl.rapidshare.com`
Mohammad