如何解析string.Format输出?

时间:2013-12-09 11:42:27

标签: c# .net parsing

我有一个包含string.Format()生成的数据的文件,每行一个,如:

Class1 [ Property1 = 123, Property2 = 124 ]
Class2 [ Property4 = 'ABCD', Property5 = 1234, Property6 = 10 ]
Class1 [ Property1 = 2, Property2 = 3 ]
Class2 [ Property4 = 'DEFG', Property5 = 2222, Property6 = 19 ]

依旧......

我需要解析它们以获取类的实例。

鉴于我有用于生成此类行的原始string.Format模板,获取原始值的最快方法是什么,以便我可以构建Class1和{{1}的实例(在这里我的意思是开发人员的时间)?

PS:我可以依赖于所有输入字符串根据模板“格式良好”的事实 PPS:我知道使用JSON会使这更简单,但现在我不能。此外我也知道Irony,但我正在寻找更快的东西(如果可能的话)。

1 个答案:

答案 0 :(得分:1)

只要你的字符串不包含特殊字符,这就是一个开头:

        var str = "Class1 [ Property1 = 123, Property2 = 124 ]";
        var m = Regex.Match(str, @"^(?<name>[^ ]+) \[ ((?<prop>[^ ]+) = (?<val>[^ ,]+),? )+\]$");
        Console.WriteLine(m.Groups["name"].Value);
        for (var i = 0; i < m.Groups["prop"].Captures.Count; i++)
        {
            Console.WriteLine(m.Groups["prop"].Captures[i].Value);
            Console.WriteLine(m.Groups["val"].Captures[i].Value);
        }

输出:

Class1
Property1
123
Property2
124

如果你的字符串确实包含特殊字符,你可以使用更复杂的正则表达式,或者你需要在状态机中逐个字符地解析字符串。第一种情况我无法回答,因为您没有提供确切的规则,您的字符串可以包含或不包含。第二种情况我无法回答,因为它太复杂了。