Find all lines that contains given string

你说的曾经没有我的故事 提交于 2019-12-23 02:33:28

问题


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

I'm trying to get all lines that contains the word "Spec" and then a space character but I get an error when I run this program.

The details of the exception are as follows:

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

Could anyone assist me on figuring out why?

Text file:

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

回答1:


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

That might work.




回答2:


This may helps:

var result = System.IO.File
    .ReadAllLines(@"data.txt")
    .Where(i => i.Contains("Spec"))
    .ToList();



回答3:


From looking at your example text file, you are starting substring one character late. The extra character is there as a string is zero-indexed

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

My test code

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

output:=      This ... bla bla



回答4:


I know this thread has been solved already but as an alternative if you want to use regex a little bit tuning is required in your existing code:

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.
}

Here:

(?<=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.

Hope it will help you even after you have solved this problem.



来源:https://stackoverflow.com/questions/16628041/find-all-lines-that-contains-given-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!