[Solved] Retrieving a portion of a url


If your URL looks like an actual URL (with the http:// part) then you could use Uri class:

private static void Extract()
{
    Uri uri = new Uri("http://somesite/somepage/johndoe21911");
    string last = uri.Segments.LastOrDefault();
    string numOnly = Regex.Replace(last, "[^0-9 _]", string.Empty);
    Console.WriteLine(last);
    Console.WriteLine(numOnly);
}

If it’s exactly like in your example (without the http:// part) then you could do something like this:

private static void Extract()
{
    string uri = "http://somesite/somepage/johndoe21911";
    string last = uri.Substring(uri.LastIndexOf("https://stackoverflow.com/") + 1);
    string numOnly = Regex.Replace(last, "[^0-9 _]", string.Empty);
    Console.WriteLine(last);
    Console.WriteLine(numOnly);
}

Above is assuming you want ALL numerics from the last segment of the URL, which is what you’ve said your requirement is. That is, if your URL were to look like this:

somesite/somepage/john123doe456"

This will extract 123456.

If you want only the last 5 characters, you could simply use string.Substring() to extract the last five characters.

If you want numerics which are at the end of the string then this would work.

private static void Extract()
{
    string uri = "somesite/somepage/john123doe21911";
    string last = uri.Substring(uri.LastIndexOf("https://stackoverflow.com/") + 1);
    string numOnly = Regex.Match(last, @"\d+$").Value;
    Console.WriteLine(last);
    Console.WriteLine(numOnly);
}

Oh and saying I’ve come across some stuff on google, but wasn’t really sure on how to implement them is a very lazy answer. If you Google you can find countless examples of how to do all these things, even on this site itself. Please from next time onward do your research first and try yourself first.

2

solved Retrieving a portion of a url