正则与普通方法对字符串过滤的比较
一、字符串替换类中的两个方法
#region 使用正则进行替换/// <summary>/// 使用正则进行替换/// </summary>/// <param name="str"></param>/// <returns></returns>public static string RegFilter(string str){string output = "";string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";output = Regex.Replace(str, Regex.Escape(pattern), "", RegexOptions.IgnoreCase | RegexOptions.Compiled);return output;}#endregion#region 使用循环替换的方式/// <summary>/// 使用循环替换的方式/// </summary>/// <param name="str"></param>/// <returns></returns>public static string Filter(string str){string output = "";string[] pattern ={"select", "insert", "delete", "from", "count\\(", "drop table", "update", "truncate","asc\\(", "mid\\(", "char\\(", "xp_cmdshell", "exec master", "netlocalgroup administrators","net user", "or ", " or ", " or", "and"};for (int i = 0; i < pattern.Length; i++){output = str.Replace(pattern[i].ToString(), "");}return output;}#endregion
二、执行方法:
static void Main(string[] args){string inputStr = @"ldklskdkfjlkinsertkkldslklkdlkldorkldklkkkdkklklorslect from kklsdklklksdlfromklksdlfjlkjskldflklkljflk*fromlikemeklkl kkwkwk kdkkjlkjlsdjf insert from oklkdllkjlkjlfjlj woinsert iselect 8 kldjlfjlkjlkjsdkljlkfjkkk and or not in kdlkjsdlfkjlk in herre lkldskjflkjlkjlkjlsdkjfljlk546546413625131651325131315143251313";StringBuilder stringBuilder1=new StringBuilder();StringBuilder stringBuilder2 = new StringBuilder();Stopwatch stopwatch=new Stopwatch();Stopwatch stopwatch2 = new Stopwatch();stopwatch.Start();for (int i = 0; i < 100000; i++){stringBuilder1.Append(StringHelper.RegFilter(inputStr));}stopwatch.Stop();Console.WriteLine("正则方法过滤所用时间:"+stopwatch.ElapsedMilliseconds);stopwatch2.Start();for (int i = 0; i < 100000; i++){stringBuilder2.Append(StringHelper.Filter(inputStr));}stopwatch2.Stop();Console.WriteLine("普通方法过滤所用时间:" + stopwatch2.ElapsedMilliseconds);Console.ReadKey();}
三、执行结果:

四、结论:
正则的方式要快很多


浙公网安备 33010602011771号