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

标签 c# regex dictionary split

我需要像这样拆分一个字符串来创建一个字典:

[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 可以被任何东西包围,例如[!# key #!] 我有兴趣将 [] 中的所有内容作为键放入字典,并将“键”之间的任何内容作为值:

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

谢谢

最佳答案

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

关于c# - 如何将字符串拆分为字典<string,string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1483532/

相关文章:

C#:使用不同的配置文件运行每个单元测试

c# - 为什么 .net 在引发 KeyNotFound 异常时不向我们提供 key (我怎样才能得到它?)

arrays - 如何返回随机字典

javascript - 删除第一个和最后一个反斜杠?

python - 如何在 Python 中解析 JSON-XML 混合文件

javascript变量传递给 map 中的php

c# - 在 C# 中使用 Plink.exe 连接到 SSH 进行测试

C#语言设计支柱

c# - MVC 4 部分 View 导致页面在提交时无响应

regex - 如何从 MATLAB 中的字符串创建首字母缩略词?