我需要像这样拆分一个字符串来创建一个字典:
[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/