views:

969

answers:

3

I need to create an dictionary by splitting a string like this:

[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

The key could be surrounded by anything if that easier, e.g. [!#key#!] i'm interested in getting everything within [] into the dictionary as keys and whatever between the “keys” as values:

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

Thanks

A: 

You can remove the first '[' and all the "]\n" for ']'

Then split you string using '[' as escape. At this time you will have an array like

key]value 0 - SenderName]Some name 1 - SenderEmail]Some email address 2 - ElementTemplate]Some text for an element

Then it's easy. Iterate through it, splitting using ']' as escape. The first element is the key, the second one will be the value.

Samuel Carrijo
A: 

Your format looks a lot similar like the Windows INI file format. Google gives me this article when I searched for "C# ini file parser". You could take some ideas from there.

Rohit
+3  A: 

C# 3.0 version -

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

Oneliner of previous version -

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

Standard C# 2.0 version -

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;
}
Matajon
+1, beat me to it by 30 seconds.
Scott Dorman