Reynaldi
Reynaldi

Reputation: 1165

Get certain part of url in C#

I need to get version no part from a url. Url will look like this "http://myweb.com/api/v1/customer". I need to get the "1" value from the url. How can i do this?

Thanks in advance

Upvotes: 1

Views: 5476

Answers (5)

AaronLS
AaronLS

Reputation: 38392

If you are using MVC you can use attribute routing:

[GET("api/v{version:int}/customer")]
public ActionResult GetCustomer(int version) {
...

https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing

Upvotes: 1

vks
vks

Reputation: 67988

(?<=v)\d+

You can use this simple regex to do that.See demo.

https://regex101.com/r/vN3sH3/36

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174844

You could use lookaround assertions like below,

Regex.Match(yourstring, @"(?<=/v)\d+(?=/)").Value;
  • (?<=/v) Positive lookbehind asserts that the match must be preceded by /v
  • \d+ Matches one or more digits.
  • (?=/) Positive lookahead asserts that the match must be followed by a forward-slash / character.

DEMO

Upvotes: 2

user1726343
user1726343

Reputation:

You can use the Uri class, which has a built in parser specifically for parsing uris, and exposes a nice API for examining the components of the URI.

Uri uri = new UriBuilder("http://myweb.com/api/v1/customer").Uri;
string versionString = uri.Segments[2]; // v1/

You can, of course, further process this to extract just the number, as shown in the next snippet. The benefit is that you won't have to worry about complicated edge cases in parsing URIs with your regex.

int version = int.Parse(Regex.Match(versionString, @"\d+").Value);

Here is a demonstration: http://ideone.com/4kgey7

Upvotes: 7

chouaib
chouaib

Reputation: 2817

string line = "http://myweb.com/api/v1/customer"
string[] arr = line.Split('\');

foreach(string str in arr)
{
    if(str[0] == 'v')
    {
       int v = Convert.ToInt32(str.SubString(1));
    }
}

Upvotes: -1

Related Questions