2013-03-02 76 views
1

我想读其中有文件在C#中的话删除#“#”附加到词,我想从文字删除此
输入文件使用正则表达式

a, 00001740, 0.125, 0,  able#1 
a, 00001740, 0.125, 0,  play#2 
a, 00002098, 0,  0.75, unable#1 

我在想这个下面有没有#格式
输出应该是这样

a, 00001740, 0.125, 0,  able 
a, 00001740, 0 .125, 0,  play 
a, 00002098, 0,  0.75, unable 

我写了下面的代码

TextWriter tw = new StreamWriter("D:\\output.txt"); 
private void button1_Click(object sender, EventArgs e) 
     { 
      if (textBox1.Text != "") 
      { 

       StreamReader reader = new StreamReader("D:\\input.txt"); 
       string line; 
       while ((line = reader.ReadLine()) != null) 
       { 
        Regex expression = new Regex(@"\b\w+(?=#\d*\b)"); 
        var results = expression.Matches(reader.ToString()) 
        foreach (Match match in results) 
        { 


         tw.Write(match); 

        } 
        tw.Write("\r\n"); 
       } 
       tw.Close(); 
       reader.Close(); 
      } 
      textBox1.Text = "";      
     } 
    } 
+0

可能是你可以替换''#和删除尾随位.. – aspiring 2013-03-02 12:29:31

回答

1

使用Regex.Replace()

string result = Regex.Replace(input, "#.*", ""); 
0

您可能需要编写一些其他的文件,因为你重写文件,而如果您不想读取并缓存文件的全部内容,那么您正在读取原始文件的内容。

另外,还要考虑这个例子:

int index = line.IndexOf("#"); 
if (index != -1) 
{ 
    line = line.Substring(0, index - 1); 
} 

在这里,您不必处理正则表达式,因此这将运行得更快。

0

你的整个代码可以有3条线路进行更换:

string txt = File.ReadAllText("D:\\input.txt"); 
txt = Regex.Replace(txt, "#.*?(\r\n|\n|$)", "$1"); 
File.WriteAllText("D:\\output.txt", txt); 
0

正则表达式替换可能是这里最好的选择。

File.WriteAllLines("c:\\output.txt", File.ReadAllLines("c:\\input.txt").Select(line => Regex.Replace(line, "#.*",""))); 

或可能TakeWhile

File.WriteAllLines("c:\\test24.txt", File.ReadAllLines("c:\\test.txt").Select(line => new string(line.TakeWhile(c => c != '#').ToArray()))); 
0

试试这个按我的意见:

 string s = "a, 00001740, 0.125, 0,  able#1"; 
     string m = Regex.Replace(s, @"#\d$", ""); 
     //for more than one digit @"#\d+$" 
     Console.WriteLine(m); 
     Console.ReadLine();