Alessandro
Alessandro

Reputation: 35

Extract Parameter from Url

I have a winform application, and I would like to parse a string that represent an URL to extract some parameters.

a sample of the URL is this:

http://www.mysite.com/itm/Sector-Watch/271443634510?pt=Orologi_da_Polso&hash=item3f334d294e

the parameter I would like to extract is 271443634510 (that is, the last part of the path before the query string).

Any idea ho how this can be done?

Upvotes: 0

Views: 742

Answers (3)

Amit Joki
Amit Joki

Reputation: 59232

You can do this:

string url = "http://www.mysite.com/itm/Sector-Watch/271443634510?pt=Orologi_da_Polso&hash=item3f334d294e";
string parameter = Regex.Match(url,"\d+(?=\?)|(?!/)\d+$").Value;

Upvotes: 1

Raging Bull
Raging Bull

Reputation: 18737

You can simply use Split function (tested and verified):

string MyUrl="http://www.mysite.com/itm/Sector-Watch/271443634510?pt=Orologi_da_Polso&hash=item3f334d294e";
string str=MyUrl.Split('/').Last().Split('?').First();

Upvotes: 0

Gigi
Gigi

Reputation: 29421

You can use Uri.Segments, which splits up the stuff after your domain into an array that includes, for your example:

  • /
  • itm/
  • Sector-Watch/
  • 271443634510

So all you need to get is the item at index 3. Working example:

    string url = "http://www.mysite.com/itm/Sector-Watch/271443634510?pt=Orologi_da_Polso&hash=item3f334d294e";
    Uri uri = new Uri(url);
    var whatYouWant = uri.Segments[3];

Upvotes: 4

Related Questions