代码之家  ›  专栏  ›  技术社区  ›  Henrik Stenbæk

如何将字符串拆分为字典<string,string>

  •  1
  • Henrik Stenbæk  · 技术社区  · 16 年前

    我需要通过拆分这样的字符串来创建字典:

    [SenderName]
    Some name
    [SenderEmail]
    Some email address
    [ElementTemplate]
    Some text for
    an element
    [BodyHtml]
    This will contain
    the html body text 
    in
    multi
    lines
    [BodyText]
    This will be multiline for text
    body
    

    如果这样容易的话,钥匙可以被任何东西包围,例如[!钥匙!] 我有兴趣把[]中的所有内容都作为键输入字典,而把键之间的任何内容作为值:

    key ::  value
    SenderName  ::  Some name
    SenderEmail  ::  Some email address
    ElementTemplate  ::  Some text for
                         an element
    

    谢谢

    3 回复  |  直到 16 年前
        1
  •  5
  •   Martin JonáÅ¡    16 年前

    C 3.0版-

    public static Dictionary<string, string> SplitToDictionary(string input)
    {
        Regex regex = new Regex(@"\[([^\]]+)\]([^\[]+)");
    
        return regex.Matches(input).Cast<Match>().ToDictionary(x => x.Groups[1].Value, x => x.Groups[2].Value.Trim());
    }
    

    以前版本的一行程序-

    public static Dictionary<string, string> SplitToDictionary(string input)
    {
        return new Regex(@"\[([^\]]+)\]([^\[]+)").Matches(input).Cast<Match>().ToDictionary(x => x.Groups[1].Value, x => x.Groups[2].Value.Trim());
    }
    

    标准C 2.0版-

    public static Dictionary<string, string> SplitToDictionary(string input)
    {
        Regex regex = new Regex(@"\[([^\]]+)\]([^\[]+)");
    
        Dictionary<string, string> result = new Dictionary<string, string>();
        foreach (Match match in regex.Matches(input))
        {
            result.Add(match.Groups[1].Value, match.Groups[2].Value.Trim());
        }
    
        return result;
    }
    
        2
  •  1
  •   Rohit    16 年前

    您的格式与 Windows INI 文件格式。谷歌给了我 this article 当我搜索“c ini文件分析器”时。你可以从那里得到一些想法。

        3
  •  0
  •   Samuel Carrijo    16 年前

    您可以删除第一个“[”和“]\n”的所有“]”

    然后使用“[”作为转义符拆分字符串。此时,您将拥有类似

    关键价值 0-sendername]某个名称 1-senderemail]一些电子邮件地址 2-elementtemplate]的一些文本 元素

    那就简单了。循环遍历,使用“]”作为转义进行拆分。第一个元素是键,第二个元素是值。