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

Hen*_*bæk 1 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
Run Code Online (Sandbox Code Playgroud)

如果更容易,键可以被任何东西包围,例如[!#key#!]我有兴趣将[]中的所有内容作为键和"键"之间的任何值作为值:

key ::  value
SenderName  ::  Some name
SenderEmail  ::  Some email address
ElementTemplate  ::  Some text for
                     an element
Run Code Online (Sandbox Code Playgroud)

谢谢

Mar*_*náš 5

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());
}
Run Code Online (Sandbox Code Playgroud)

以前版本的Oneliner -

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());
}
Run Code Online (Sandbox Code Playgroud)

标准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;
}
Run Code Online (Sandbox Code Playgroud)