problem with regular expression replacement
I'm trying to make a program to go through a lot of .sql files and replace names for example view_name to [dbo].[view_name]. So far it replaces most of the words, however if a name contains number in brackets like (3) or (7) and so on it wont replace anything within that file. I've provided the code below.
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.GetFileNameWithoutExtens开发者_StackOverflowion(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);
}
}
}
You should Escape
the characters when building a regex pattern:
string pattern = "\\s" + Regex.Escape(tempNameNoExtens);
精彩评论