【问题标题】:Getting multiple substrings from single string C#从单个字符串 C# 获取多个子字符串
【发布时间】:2014-05-23 15:32:14
【问题描述】:

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

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 的功能。

【问题讨论】:

  • 发布您用于解析字符串的函数代码。
  • 我尝试了一些不同的功能,但都没有成功。最新的只是获得第一对。

标签: c# string substring keyvaluepair


【解决方案1】:
var repspl = mydata.Split(';').Select( x =>  new { Key = x.Split(',')[0], Value = x.Split(',')[1] });

【讨论】:

  • 每个人的解决方案都很棒,但我最终还是选择了 Kevin Cook 的,因为它是单行的,而且这个东西已经很臃肿了。类中的大多数其他函数都使用列表,这非常简洁地生成了一个列表。谢谢大家的回答。谢谢,凯文。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    您可以像本例中那样对数组使用 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

    【讨论】:

      【解决方案4】:

      您可以在 .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();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-28
        • 2019-02-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多