我正在尝试制作一个程序来浏览很多.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);
}
}
}
答案 0 :(得分:1)
构建正则表达式模式时,您应该Escape
个字符:
string pattern = "\\s" + Regex.Escape(tempNameNoExtens);