C# 将具有特定模式的字符串分隔到字典中

C# 将具有特定模式的字符串分隔到字典中,c#,string,design-patterns,C#,String,Design Patterns,用户输入以下内容: {YYYY}./.{mm}-{CNo}\/{WEPNo}#{XNo+YNo} 您将如何读取这样的字符串并将其分离到字典中,如下所示: new Dictionary<String, String>() { {"YYYY", "./." }, {"mm", "-"}, {"CNo", @"\/"}, {"WEPNo", "#"}, {"XNo+YNo", ""} }; var input = @"{YYYY}./.{mm}-{CNo}\/{WE

用户输入以下内容:

{YYYY}./.{mm}-{CNo}\/{WEPNo}#{XNo+YNo}
您将如何读取这样的字符串并将其分离到字典中,如下所示:

new Dictionary<String, String>() {
  {"YYYY", "./." },
  {"mm", "-"},
  {"CNo", @"\/"},
  {"WEPNo", "#"},
  {"XNo+YNo", ""}
};
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);
newdictionary(){
{“yyy”,“/”},
{“mm”,“-”},
{“CNo”,@“\/”},
{“WEPNo”,“#”},
{“XNo+YNo”,“”
};

我可能会使用正则表达式来解析输入字符串。 然后,我将创建一个包含所有值的类,并重写
.ToString()
方法以输出回其原始字符串值


此外,您可能应该至少显示输入字符串的一个“示例”值。否则,要解释您的问题并提供基于代码的可靠答案有些困难。

使用正则表达式:

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);
}
var-input=@“{YYYY}./.{mm}-{CNo}\/{WEPNo}{XNo+YNo}”;
Dictionary Dictionary=新字典();
正则表达式=新正则表达式(@“\{(?+?)\}(?[^{]*)”;
foreach(在ex.Matches中匹配(输入))
{
添加(match.Groups[“key”].Value,match.Groups[“Value”].Value);
}

结合正则表达式和LINQ,您可以这样做:

new Dictionary<String, String>() {
  {"YYYY", "./." },
  {"mm", "-"},
  {"CNo", @"\/"},
  {"WEPNo", "#"},
  {"XNo+YNo", ""}
};
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);
var-input=@“{YYYY}./.{mm}-{CNo}\/{WEPNo}{XNo+YNo}”;
正则表达式=新正则表达式(@“\{(?.+?)\}(?[^{}]*);
var dictionary=ex.Matches(输入).Cast()
.ToDictionary(m=>m.Groups[“key”].Value,m=>m.Groups[“Value”].Value);

期望结果中的键和值是什么?从您的示例中不清楚。键是括号{},其内容类似于“YYYY”。值总是在括号“}”之后。如何将键读入带括号的词典?