Reputation: 1165
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
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
Reputation: 67988
(?<=v)\d+
You can use this simple regex to do that.See demo.
https://regex101.com/r/vN3sH3/36
Upvotes: 0
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.Upvotes: 2
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
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