找到包含给定字符串的所有行 [英] Find all lines that contains given string

查看:136
本文介绍了找到包含给定字符串的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  System.IO.StreamReader file = new System.IO.StreamReader(@data.txt); 
列表< String> Spec = new List< String>();
while(file.EndOfStream!= true)
{
string s = file.ReadLine();
匹配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);




$ b $ p
$ b我试图让所有包含单词Spec,然后是一个空格字符,但是当我运行这个程序时出现错误。

异常的细节如下:
$ b $ p $ 一个未处理的类型异常mscorlib.dll中出现'System.ArgumentOutOfRangeException'



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

文本文件:

  ID 560 
规格这个... bla bla

blah ...
blah ...
bla bla
bla
分类其他
价格$ 259.95


ID 561
规格更多等等等等...

等等...
等等...
bla bla
bla
类别其他
价格$ 229.95


解决方案

System.IO.StreamReader file = new System.IO.StreamReader(data.txt);
列表< string> Spec =新列表< string>();
while(!file.EndOfStream)
{
if(file.ReadLine()。Contains(Spec))
{
Spec.Add(s。子字符串(5,s.Length - 5));


$ / code $ / pre
$ b $ p

这可能会奏效。 b

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

解决方案

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.

这篇关于找到包含给定字符串的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆