1

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.

natep
  • 126
  • 4
  • 13

5 Answers5

1
var repspl = mydata.Split(';').Select( x =>  new { Key = x.Split(',')[0], Value = x.Split(',')[1] });
Kevin Cook
  • 1,922
  • 1
  • 15
  • 16
  • Everyone's solutions were excellent, but I ultimately went with Kevin Cook's because it was a single line and this thing is already bloated. Most of the other functions within the class use Lists, and this generated a list very succinctly. Thanks for the answer, everyone. Thanks, Kevin. – natep May 23 '14 at 17:18
0

You could do something fun, like:

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

var attributes =  Regex.Match(pairs, @"\((.*?)\)").Groups[1].Value.Split(';')
    .Select(pair => pair.Split(','))
    .Select(pair => new { Attribute = pair[0], Value = pair[1] });
Dave Bish
  • 19,263
  • 7
  • 46
  • 63
0

You can use split function with an array like in this example :

using System;

public class SplitTest {
    public static void Main() {

        string words = "This is a list of words, with: a bit of punctuation" +
                       "\tand a tab character.";

        string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });

        foreach (string s in split) {

            if (s.Trim() != "")
                Console.WriteLine(s);
        }
    }
}
// The example displays the following output to the console:
//       This
//       is
//       a
//       list
//       of
//       words
//       with
//       a
//       bit
//       of
//       punctuation
//       and
//       a
//       tab
//       character

This is from : http://msdn.microsoft.com/fr-fr/library/b873y76a(v=vs.110).aspx

Alexein1
  • 109
  • 1
  • 6
0

You can use a combination of a regex and a cool use of capture capabilities in the .net regex engine:

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

//This would capture each key in a <attr> named group and each 
//value in a <val> named group
var groups = Regex.Match(
    pairs, 
    @"\((?:(?<attr>[^),]+?),(?<val>[^);]+?)(?:;|\)))*");

//Because each group's capture is stored in .net you can access them and zip them into one list.
var yourList = 
    Enumerable.Zip
    (
        groups.Groups["attr"].Captures.Cast<Capture>().Select(c => c.Value), 
        groups.Groups["val"].Captures.Cast<Capture>().Select(c => c.Value), 
        (attr, val) => new KeyValuePair<string, string>(attr, val)
    ).ToList();
Farhad Alizadeh Noori
  • 2,276
  • 17
  • 22
0
string pairs = "image_attribs(color,purple;size,large).jpg";

// Remove the prefix and suffix of the string
int startIndex = pairs.IndexOf("(") + 1;
int endIndex = pairs.LastIndexOf(")");
string pairsSubstring = pairs.Substring(startIndex, endIndex - startIndex);

// Split the string on semicolon to get individual pairs
string[] pairStrings = pairsSubstring.Split(';');

// Iterate over each pair and extract the name and value
List<KeyValuePair<string, string>> attributes = new List<KeyValuePair<string, string>>();
foreach (string pairString in pairStrings)
{
    // Split the pair on comma to separate the name and value
    string[] parts = pairString.Split(',');

    // Trim any leading or trailing whitespace
    string name = parts[0].Trim();
    string value = parts[1].Trim();

    // Add the pair to the attributes list
    attributes.Add(new KeyValuePair<string, string>(name, value));
}

This code will extract the name/value pairs from the string and create a list of KeyValuePairs where each KeyValuePair represents a pair in the format of <name, value>. You can then use the attributes list for further processing or manipulation as needed.

Note: This code assumes that the string format remains consistent, with name/value pairs separated by a comma and semicolon, enclosed in parentheses. Make sure to handle any variations in the string format accordingly. // Now you have a list of KeyValuePairs representing the name/value pairs