从文件中获取数据并拆分为数组

时间:2015-02-22 02:19:32

标签: c# regex

我在网页上格式化的信息如下所示:

Key=submission_id, Value=300348811884547965
Key=formID, Value=50514289063151
Key=ip, Value=xxxxx
Key=editimage, Value=Yes
Key=openimage5, Value=Yes
Key=copyimage, Value=Yes

我如何获取每一行的值,我在考虑做某种next(),同时在每行的第二个等号之后获取所有数据但是我不确定如何在c#中执行它。我确信有一个更好的解决方案,然后我想到的。请让我知道你的想法。

1 个答案:

答案 0 :(得分:1)

正则表达式可以很好地解析以这种方式构造的数据。

        Regex splitter = new Regex(@"Key=([\w]+), Value=([\w]+)");

        string path = "TextFile1.txt";
        string[] lines = System.IO.File.ReadAllLines(path);
        lines.ToList().ForEach((s) =>
        {
            Match match = splitter.Match(s);
            if (match.Success)
            {
                Console.WriteLine("The Key is " + match.Groups[1] + " and the value is " + match.Groups[2]);
            }
        });