1
System.IO.StreamReader file = new System.IO.StreamReader(@"data.txt");
List<String> Spec= new List<String>();
while (file.EndOfStream != true)
{
    string s = file.ReadLine();
    Match m = Regex.Match(s, "Spec\\s");
    if (m.Success)
    {
        int a = Convert.ToInt16(s.Length);
        a = a - 5;
        string part = s.Substring(5, a);
        Spec.Add(part);
     }
}

我正在尝试获取包含单词“Spec”和空格字符的所有行,但是当我运行该程序时出现错误。

异常详情如下:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

任何人都可以帮助我找出原因吗?

文本文件:

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
4

4 回答 4

3

这可能会有所帮助:

var result = System.IO.File
    .ReadAllLines(@"data.txt")
    .Where(i => i.Contains("Spec"))
    .ToList();
于 2013-05-18T19:16:40.357 回答
2
System.IO.StreamReader file = new System.IO.StreamReader("data.txt");
List<string> Spec = new List<string>();
while (!file.EndOfStream)
{
    if(file.ReadLine().Contains("Spec")) 
    {
        Spec.Add(s.Substring(5, s.Length - 5));
    }
}

那可能行得通。

于 2013-05-18T19:19:01.240 回答
1

通过查看您的示例文本文件,您开始晚一个字符的子字符串。额外的字符在那里,因为字符串是零索引的

string part = s.Substring(4, s.Length - 4);

我的测试代码

 string s = "Spec    This ... bla bla"; 
 Console.WriteLine(s.Substring(4,s.Length-4));
 Console.ReadLine();

output:=      This ... bla bla
于 2013-05-18T19:31:38.957 回答
1

我知道这个线程已经解决了,但是如果您想使用正则表达式,则需要在现有代码中进行一些调整:

System.IO.StreamReader file = new System.IO.StreamReader(@"data.txt");
List<String> Spec= new List<String>();
while (file.EndOfStream != true)
{
    string s = file.ReadLine();
    Match m = Regex.Match(s, "(?<=Spec\s)(.)+");
    if (m.Success)
    {
        Spec.Add(m.ToString());
    }

    s = String.Empty; // do not forget to free the space you occupied.
}

这里:

(?<=Spec\s) : This part looks for the text "Spec " in line. 
              Also known as positive look behind.

(.)+        : If first part satisfies take the whole line as a matched string. "." matches 
              every thing except newline.

希望即使您解决了这个问题,它也会对您有所帮助。

于 2013-05-19T13:00:34.377 回答