Regular Expression and special characters
It is a lot of fun to work with Regular expressions. They are slick, fast, and unstable when the underlying format changes. What else a developer could ask for?
In my current project, one of our developers stores a large SQL statement in his config file. The statement is formatted for readability. But when he executes his statement, he did not want the new lines and tabs.
I suggested using Regular Expressions. Since he is new to this area, I volunteered to help him out.
At first my code looked as below:
System.IO.StreamReader myFile =new System.IO.StreamReader(@"c:\BG\a.txt");string myString = myFile.ReadToEnd();myFile.Close();textBox1.Text = myString;myString = System.Text.RegularExpressions.Regex.Replace(myString,"\t","");myString = System.Text.RegularExpressions.Regex.Replace(myString,"\r\n","");myString = System.Text.RegularExpressions.Regex.Replace (myString," ","");textBox2.Text = myString;
He was happy with the outcome. Still, I wanted a single regular expression to perform this task. After a bit of digging, I came up with the following statement:
//Regular expression to eliminate new line, carriage returns, tabs, and multiple white spaces
myString = System.Text.RegularExpressions.Regex.Replace (myString,"\t\r\n ","");
I am happy! I hope this gives you an idea of how to create sets of characters for find and replace in regular expression. I could have used other choices like concatenating the find results into a string. But, it would take more coding.
If you can suggest a better solution, I am listening. :-)