1

我使用字符串来表示图像文件名中的名称/值对。

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

我需要解析该字符串以获取分号前后的名称/值对。我可以拆分分号并减去左括号的长度,但我希望相应的函数可以扩展到多对。

我需要想出一个可以返回这些对的多子字符串函数。然后,我将它们设为 KeyValuePairs 列表:

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

当前解析仅获取第一对:

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

我已经拥有解析逗号分隔对以创建和添加新 KeyValuePair 的功能。

4

4 回答 4

1
var repspl = mydata.Split(';').Select( x =>  new { Key = x.Split(',')[0], Value = x.Split(',')[1] });
于 2014-05-23T16:14:33.823 回答
0

你可以做一些有趣的事情,比如:

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] });
于 2014-05-23T15:41:09.993 回答
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

于 2014-05-23T15:52:09.850 回答
0

您可以在 .net 正则表达式引擎中结合使用正则表达式和酷炫的捕获功能:

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();
于 2014-05-23T16:22:05.730 回答