Removing special chars using Regex January, 2007
Removing special chars (Control chars 0-31 and extended ASCII 127-255) is pretty easy to do with a regular expression. Simply select chars that are not in the range of ASCII 32-126 (Hex 20-7E) and replace these chars with an empty string.
Regex SpecialCharExpression = new Regex(@"[^\x20-\x7E]");
string NewData = SpecialCharExpression.Replace(OldData, string.Empty);
Here is a working example:
class Program
{
static void Main(string[] args)
{
string OldData = string.Empty;
for (int Index = 0; Index < 256; Index++)
{
OldData += ((char)Index).ToString();
}
Regex SpecialCharExpression = new Regex(@"[^\x20-\x7E]");
string NewData = SpecialCharExpression.Replace(OldData, string.Empty);
Console.WriteLine("Length: " + NewData.Length);
Console.WriteLine(NewData);
Console.ReadKey();
}
}