c#正则表达式替换问题
本文关键字:问题 替换 正则表达式 | 更新日期: 2023-09-27 18:19:09
我正试图编写一个程序,可以替换文本和替换也Regex文本。所以我有麻烦与正则表达式替换部分。我是一个真正的新手:)
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");
}
//这是REGEX替换:
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.");
}
}
Regex替换函数可以在MSDN正则表达式替换文档中找到。
使用: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);
}
}