2011-12-30 64 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