0

I have string templates that can be in any of these below 3 forms. How can I extract the list of strings that are enclosed between the parenthesis? I need the output from all of these strings to be same which is

{CustID}, {Name}, {Contact}, {Address1}, {Address2}

Examples:

/Customer/Initiation/{CustID}?Name={Name}&Contact={Contact}&Address1={Address1}&Address2={Address2}

/Customer/Initiation/{CustID}/{Name}?Contact={Contact}&Address1={Address1}&Address2={Address2}

/Customer/Initiation/{CustID}/{Name}/{Contact}?Address1={Address1}&Address2={Address2}

I found out that there is a utility in asp net core which can parse a query string and produce a list of key/value pairs. But in my case, it can't parse {string} that are not in the key/value format in the url template. Is there a way to achieve this without using Regex ?

Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery()

Thanks for any suggestions!

Jyina
  • 2,530
  • 9
  • 42
  • 80
  • Just a thought, if you are trying to achieve it with Web API and you are creating specific endpoints you can do that with RouteAttribute and FromQueryAttribute. I wrote that because it seems that you are manipulating different resources with query params – LukaszBalazy Jun 08 '20 at 21:13
  • check out the parsing code in the second answer here https://stackoverflow.com/questions/1010123/named-string-format-is-it-possible – pm100 Jun 08 '20 at 21:17
  • Any reason why you don't want to use `Regex`? – Joshua Robinson Jun 08 '20 at 22:07
  • 1
    No, there is no reason for not using Regex. I was just wondering if there is any utility from .net framework. If Regex is the better option here, I will go with that one. Thanks! – Jyina Jun 09 '20 at 14:09

2 Answers2

1

You can use a regular expression to find the desired parts of the text:

var test = Regex.Matches(yourString, @"{\w+}");

foreach(var t in test)
{
    Console.WriteLine(t);
}
SBFrancies
  • 3,987
  • 2
  • 14
  • 37
1

Well, since you specified without Regex, you could use a combination of String.IndexOf(char, int) and String.Substring(int, int) to parse the templates out of the source string. It might look something like this...

private static IEnumerable<string> ParseTemplates(string source)
{
    if (source is null)
    {
        throw new ArgumentNullException(nameof(source)); //Or an empty enumerable.
    }
    var result = new List<string>();
    int currentIdx = 0;
    while ((currentIdx = source.IndexOf('{', currentIdx)) > -1)
    {
        int closingIdx = source.IndexOf('}', currentIdx);
        if (closingIdx < 0)
        {
            throw new InvalidOperationException($"Parsing failed, no closing brace for the opening brace found at: {currentIdx}");
        }
        result.Add(source.Substring(currentIdx, closingIdx - currentIdx + 1));
        currentIdx = closingIdx;
    }
    return result;
}
Joshua Robinson
  • 3,399
  • 7
  • 22