// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Text; using System.Text.RegularExpressions; namespace E { public class Program { public static string Strip1(string str) { return Regex.Replace(str, @"[^\w-]+", ""); } public static string Strip2(string str) { StringBuilder sb = new StringBuilder(str.Length); foreach (char ch in str) { if (Char.IsLetterOrDigit(ch) || ch == '-' || ch == '_') { sb.Append(ch); } } return sb.ToString(); } private static Regex re = new Regex(@"[^\w-]+", RegexOptions.Compiled); public static string Strip3(string str) { return re.Replace(str, ""); } private const string TEST_STR = "AB&*^#Cabc(#&123--__"; private const int N = 1000000; public static void Main(string[] args) { Console.WriteLine(Strip1(TEST_STR)); Console.WriteLine(Strip2(TEST_STR)); Console.WriteLine(Strip3(TEST_STR)); DateTime dt1 = DateTime.Now; for(int i = 0; i < N; i++) { Strip1(TEST_STR); } DateTime dt2 = DateTime.Now; Console.WriteLine((dt2 - dt1).TotalSeconds); DateTime dt3 = DateTime.Now; for(int i = 0; i < N; i++) { Strip2(TEST_STR); } DateTime dt4 = DateTime.Now; Console.WriteLine((dt4 - dt3).TotalSeconds); DateTime dt5 = DateTime.Now; for(int i = 0; i < N; i++) { Strip3(TEST_STR); } DateTime dt6 = DateTime.Now; Console.WriteLine((dt6 - dt5).TotalSeconds); } } }