Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Caputure correct part of string based on it's relationship

I am receiving the following response header from an API request (as String):

<https://example1>; rel="previous", <https://example2>; rel="next"

I need to capture the url that relates only to the "next" rel attribute.
I know I can dig that url out of the string as is but I cannot guarantee they will be returned in the order prev, next.

What is a good way to ensure I capture the correct url that is associated with the next param?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I would prefer to know how to do this in vb but am happy to translate a C# answer.

>Solution :

Looking at your example shows me that the "parts" of previous and next are separated by a comma, so we can split the string into two at the comma, find which one contains rel="next", then substring inside it to get the URL, something like

const string response = "<https://example1>; rel=\"previous\", <https://example2>; rel=\"next\"";
var split = response.Split(',');

var url = string.Empty;
foreach (var part in split)
{
    var trimmed = part.Trim();
    if (!trimmed.Contains("rel=\"next\""))
        continue;

    url = trimmed.Substring(0, trimmed.IndexOf(';'));
    url = url.TrimStart('<');
    url = url.TrimEnd('>');
}

Console.WriteLine(url);

Check out the demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading