开发者

Separate a string with a certain pattern into a dictionary

The user enter this:

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

How would you read and s开发者_如何学JAVAeparate such a string into a dictionary like this:

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


Combing regular expressions and LINQ you can do it like this:

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


by using regular expressions:

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


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


I would probably use regular expressions to parse the input string. Then, I would create a class that had all of the values, and override the .ToString() method to output back to its original string value.

Also, you should probably show at least one "Example" value of the input string. Otherwise, it's somewhat difficult to interpret your question and provide a solid, code-based answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜