Search code examples
c#stringsubstringkeyvaluepair

Getting multiple substrings from single string C#


I'm using a string to represent name/value pairs in an image filename.

string pairs = image_attribs(color,purple;size,large).jpg;

I need to parse that string to get the name/value pairs from before and after the semicolon. I can split on the semicolon and subtract the length to the opening parenthesis, but I'd like the corresponding function to be scalable to multiple pairs.

I need to come up with a multiple substring function that can return those pairs. I will then make them a list of KeyValuePairs:

List<KeyValuePair<string, string>> attributes = new List<KeyValuePair<string, string>>();

The current parsing which gets only the first pair:

string attribs = imagepath.Substring(imagepath.IndexOf("(") +1, imagepath.IndexOf(";" - imagepath.IndexOf("(");

I already have the function to parse the comma-separated pairs to create and add new KeyValuePairs.


Solution

  • var repspl = mydata.Split(';').Select( x =>  new { Key = x.Split(',')[0], Value = x.Split(',')[1] });