0

对不起我的英语不好,如果可以的话,请帮忙。

  private void button1_Click(object sender, EventArgs e)
            {
                 if (File.Exists(@"data.txt"))
                {
                    System.IO.StreamReader file = new System.IO.StreamReader(@"data.txt");

                     while (file.EndOfStream != true)
                      {
                        string s = file.ReadLine();
                        string s2 = file.ReadLine();
                        string s3 = file.ReadLine();
                        string s4 = file.ReadLine();

                        Match m = Regex.Match(s, "ID\\s");
                        Match m2 = Regex.Match(s2, "Spec\\s");
                        Match m3 = Regex.Match(s3, "Category\\s");
                        Match m4 = Regex.Match(s4, "Price\\s");

                        if (m.Success && m2.Success && m3.Success && m4.Success)
                        {

                             // some code 

                        }
                      }
                }
                if (!File.Exists(@"data.txt")) MessageBox.Show("The file is missing!");
            }

文本文件内容:

ID  560
Spec    This ... bla bla 

blah...
blah...
bla bla 
bla
Category    Other
Price   $259.95 


ID  561
Spec    more blah blah...

blah...
blah...
bla bla 
bla
Category    Other
Price   $229.95

我只想得到文本之后,直到之后ID的所有内容。在这个例子中(上面)我需要:SpecCategory

560  

This ... bla bla 

    blah...
    blah...
    bla bla 
    bla


561

more blah blah...

    blah...
    blah...
    bla bla 
    bla

依此类推,直到到达文件末尾。

4

1 回答 1

0

我像这样解析了一堆文件。使用文本阅读器将数据读入 Ienumerable,如下所示。这不是工作代码,而是为您提供概念。它应该让你朝着正确的方向前进。

 TextReader reader = new StreamReader(path);
 IEnumerable<string> data = this.ReadLines(reader);  

 foreach (var s in data){
     // make sure its not null doesn't start with an empty line or something.
     if (s != null && !string.IsNullOrEmpty(s) && !s.StartsWith("  ") && s.Length > 0){
        s = s.ToLower().Trim();

        // use regex to find some key in your case the "ID".
        // look into regex and word boundry find only lines with ID
        // double check the below regex below going off memory. \B is for boundry
        var regex = new Regex("\BID\B");
        var isMatch = regex.Match(s.ToLower());
        if(isMatch.Success){ 
           // split the spaces out of the line.
           var arr = s.split(' ');
           var id = arr[1]; // should be second obj in array.

        }

     }
 }

这是我在实际项目中使用的一个解析文件,它解析这种类型的文本文件。它使用 xml 文件进行模板化,以便该文件可用于各种文件。但是,它会让您了解什么是可能的,或者其他一些可以提供帮助的想法。解析器

于 2013-05-18T01:28:12.493 回答