从单个字符串C#获取多个子字符串

时间:2014-05-23 15:32:15

标签: c# string substring keyvaluepair

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

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("(");

我已经有了解析逗号分隔对的函数来创建和添加新的KeyValuePairs。

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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] });

答案 2 :(得分:0)

您可以将split函数与数组一起使用,如下例所示:

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

来自:http://msdn.microsoft.com/fr-fr/library/b873y76a(v=vs.110).aspx

答案 3 :(得分:0)

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

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