正则表达式替换问题
本文关键字:问题 替换 正则表达式 | 更新日期: 2023-09-27 17:58:19
我正试图制作一个程序来遍历大量.sql文件,并将名称(例如view_name)替换为[dbo]。[view_name]。到目前为止,它替换了大多数单词,但是,如果名称中包含括号中的数字,如(3)或(7)等,它不会替换该文件中的任何内容。我提供了以下代码。
FolderBrowserDialog fb = new FolderBrowserDialog();
fb.ShowDialog();
string directory = fb.SelectedPath;
if(directory != String.Empty)
{
DirectoryInfo di = new DirectoryInfo(directory);
FileInfo fi = new FileInfo(directory);
FileInfo[] fiArray = di.GetFiles();
for (int i = 0; i < fiArray.Length; i++)
{
string result;
//StreamReader
using (StreamReader sr = new StreamReader(directory + "''" + fiArray[i].ToString()))
{
string temp = sr.ReadToEnd();
string tempNameExtens = fiArray[i].Name;
string tempNameNoExtens = Path.GetFileNameWithoutExtension(fiArray[i].Name);
MessageBox.Show(tempNameNoExtens);
string pattern = "''s" + tempNameNoExtens;
string replace = " [dbo].[" + tempNameNoExtens + "]";
Regex rgx = new Regex(pattern);
result = rgx.Replace(temp, replace);
}
//StreamWriter
using (StreamWriter sw = new StreamWriter(directory + "''" + fiArray[i].ToString()))
{
sw.WriteLine(result);
}
}
}
构建正则表达式模式时,应该Escape
字符:
string pattern = "''s" + Regex.Escape(tempNameNoExtens);