[英]How to split string into a Dictionary<string,string>
我需要通過分割這樣的字符串來創建字典:
[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 :: 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());
}
先前版本的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());
}
標准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;
}
您的格式看起來很像Windows INI文件格式。 當我搜索“ C#ini文件解析器”時,Google給我這篇文章 。 您可以從那里獲取一些想法。
您可以刪除第一個'['和所有'] \\ n'的']'
然后使用'['作為轉義符將字符串拆分。 此時,您將擁有一個類似
鍵]值0-SenderName]某些名稱1-SenderEmail]某些電子郵件地址2-ElementTemplate]元素的某些文本
那很容易。 遍歷它,使用']'作為轉義進行拆分。 第一個元素是鍵,第二個元素是值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.