2011-02-15 49 views
1

用戶輸入:獨立的具有一定模式的字符串轉換成字典

{YYYY}./.{mm}-{CNo}\/{WEPNo}#{XNo+YNo} 

你如何閱讀和獨立這樣的字符串轉換成字典是這樣的:

new Dictionary<String, String>() { 
    {"YYYY", "./." }, 
    {"mm", "-"}, 
    {"CNo", @"\/"}, 
    {"WEPNo", "#"}, 
    {"XNo+YNo", ""} 
}; 
+2

的關鍵是什麼,什麼是在預期結果的價值?從你的例子中不清楚。 – 2011-02-15 12:25:17

+0

關鍵是括號{}及其內容,如「YYYY」。該值總是在括號'}' – msfanboy 2011-02-15 12:27:26

回答

2

梳理正則表達式和LINQ,你可以做這樣的:

var input = @"{YYYY}./.{mm}-{CNo}\/{WEPNo}#{XNo+YNo}"; 
Regex ex = new Regex(@"\{(?<key>.+?)\}(?<value>[^{}]*)"); 
var dictionary = ex.Matches(input).Cast<Match>() 
    .ToDictionary(m => m.Groups["key"].Value, m => m.Groups["value"].Value); 
0
String str = @"{YYYY}./.{mm}-{CNo}\/{WEPNo}#{XNo+YNo}"; 

var dict = str.Split(new String[] { "{" }, StringSplitOptions.RemoveEmptyEntries) 
    .Select(s => String.Concat("{", s)) 
    .Select(s => new 
    { 
     key = String.Concat(s.Split(new String[] { "}" }, StringSplitOptions.None)[0], "}"), 
     value = s.Split(new String[] { "}" }, StringSplitOptions.None)[1], 
    }) 
    .ToDictionary(s => s.key, s => s.value); 
0

我可能會使用正則表達式來解析輸入字符串。 然後,我將創建一個具有所有值的類,並覆蓋.ToString()方法以返回其原始字符串值。

此外,您應該至少顯示一個輸入字符串的「示例」值。否則,解釋你的問題並提供一個堅實的,基於代碼的答案有點困難。

1

使用正則表達式:

var input = @"{YYYY}./.{mm}-{CNo}\/{WEPNo}#{XNo+YNo}"; 

Dictionary<string, string> dictonary = new Dictionary<string, string>(); 
Regex ex = new Regex(@"\{(?<key>.+?)\}(?<value>[^{]*)"); 

foreach (Match match in ex.Matches(input)) 
{ 
    dictonary.Add(match.Groups["key"].Value, match.Groups["value"].Value); 
}