2011-12-30 62 views
0

我想寫一個程序,可以替換文本並替換正則表達式文本。 所以我有正則表達式替換麻煩一個part..I'm真正的菜鳥:)c#正則表達式替換問題

private void button2_Click(object sender, EventArgs e) 
{ 
    if (File.Exists(textBox1.Text)) 
    { 

//這是常規的更換:

 if (checkBox1.Checked == false) 
     { 
      StreamReader sr = new StreamReader(textBox1.Text); 
      StreamWriter sw = new StreamWriter(textBox1.Text.Replace(".", "_new.")); 
      string cur = ""; 
      do 
      { 
       cur = sr.ReadLine(); 
       cur = cur.Replace(textBox2.Text, textBox3.Text); 
       sw.WriteLine(cur); 
      } 
      while (!sr.EndOfStream); 

      sw.Close(); 
      sr.Close(); 

      MessageBox.Show("Finished, the new file is in the same directory as the old one"); 
     } 

//這是正則表達式替換:

 if (checkBox1.Checked == true) 
     { 
      System.Text.RegularExpressions.Regex g = new Regex(@textBox2.Text); 
      using (StreamReader r = new StreamReader(textBox1.Text)) 
      { 
       StreamReader sr = new StreamReader(textBox1.Text); 
       StreamWriter sw = new StreamWriter(textBox1.Text.Replace(".", "_new.")); 
       string cur = ""; 
       do 
       { 
        cur = sr.ReadLine(); 
        cur = cur.Replace(textBox2.Text, textBox3.Text); 
        sw.WriteLine(cur); 
       } 
       while (!sr.EndOfStream); 

       sw.Close(); 
       sr.Close(); 

      } 
      MessageBox.Show("Finished, the new file is in the same directory as the old one"); 
     } 


     button2.Enabled = false; 
    } 
    if (File.Exists(textBox1.Text) == false) 
    { 
    MessageBox.Show("Please select a file and try again."); 

    } 
} 
+0

這裏沒有問題。請具體說明問題所在。如果您收到例外情況,請提供詳細信息以及投放位置。 – Jay 2011-12-30 14:24:41

+1

據我所見,除了實例化你的正則表達式之外,你沒有做任何事... – canon 2011-12-30 14:28:17

+0

問題是什麼?我很想回應,因爲我認爲我看到了這個問題,但我會表現出剋制......沒有不好的非問題的回報...... – 2011-12-30 14:29:42

回答

2

正則表達式替換功能可以在MSDN Regular Expression Replace找到文檔。

用途:Regex.Replace(input, pattern, replacement);

string inputFilename = textBox1.Text; 
string outputFilename = inputFilename.Replace(".", "_new."); 
string regexPattern = textBox2.Text; 
string replaceText = textBox3.Text; 

using (StreamWriter sw = new StreamWriter(outputFilename))) 
{ 
    foreach (string line in File.ReadAllLines(inputFilename)) 
    { 
     string newLine = Regex.Replace(line, regexPattern, replaceText); 
     sw.WriteLine(newLine); 
    } 
} 
+0

我只是不能把它放在上下文中。我希望它在文件的所有行上循環 – Zbone 2011-12-30 15:19:17

+0

現在添加一個更完整的示例。 – 2011-12-30 15:39:11

+0

(可選)您可以使用File.ReadAllText並在整個文件中一次運行表達式。 – TrueWill 2011-12-30 16:34:02