2013-03-02 72 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();