Jyina
Jyina

Reputation: 2902

How to extract strings enclosed between two characters?

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!

Upvotes: 1

Views: 521

Answers (2)

Joshua Robinson
Joshua Robinson

Reputation: 3539

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;
}

Upvotes: 1

SBFrancies
SBFrancies

Reputation: 4240

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);
}

Upvotes: 2

Related Questions