user2395751
user2395751

Reputation: 35

Find all lines that contains given string

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

Upvotes: 1

Views: 8392

Answers (4)

NeverHopeless
NeverHopeless

Reputation: 11233

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.

Upvotes: 1

Sayse
Sayse

Reputation: 43300

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

Upvotes: 1

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

This may helps:

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

Upvotes: 3

Raz Harush
Raz Harush

Reputation: 739

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.

Upvotes: 2

Related Questions