• 正则与普通方法对字符串过滤的比较


    一、字符串替换类中的两个方法

     
    1. #region 使用正则进行替换
    2. /// <summary>
    3. /// 使用正则进行替换
    4. /// </summary>
    5. /// <param name="str"></param>
    6. /// <returns></returns>
    7. public static string RegFilter(string str)
    8. {
    9. string output = "";
    10. string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
    11. output = Regex.Replace(str, Regex.Escape(pattern), "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    12. return output;
    13. }
    14. #endregion
    15. #region 使用循环替换的方式
    16. /// <summary>
    17. /// 使用循环替换的方式
    18. /// </summary>
    19. /// <param name="str"></param>
    20. /// <returns></returns>
    21. public static string Filter(string str)
    22. {
    23. string output = "";
    24. string[] pattern =
    25. {
    26. "select", "insert", "delete", "from", "count\(", "drop table", "update", "truncate",
    27. "asc\(", "mid\(", "char\(", "xp_cmdshell", "exec master", "netlocalgroup administrators",
    28. "net user", "or ", " or ", " or", "and"
    29. };
    30. for (int i = 0; i < pattern.Length; i++)
    31. {
    32. output = str.Replace(pattern[i].ToString(), "");
    33. }
    34. return output;
    35. }
    36. #endregion


    二、执行方法:

       
    1. static void Main(string[] args)
    2. {
    3. string inputStr = @"ldklskdkfjlkinsertkkldslklkdlkldorkldklkkkdkklklorslect from kklsdklklksdlfromklksdlfjlkjskldflklkljflk*fromlikemeklkl kkwkwk kdkkjlkjlsdjf insert from oklkdllkjlkjlfjlj woinsert iselect 8 kldjlfjlkjlkjsdkljlkfjkkk and or not in kdlkjsdlfkjlk in herre lkldskjflkjlkjlkjlsdkjfljlk546546413625131651325131315143251313";
    4. StringBuilder stringBuilder1=new StringBuilder();
    5. StringBuilder stringBuilder2 = new StringBuilder();
    6. Stopwatch stopwatch=new Stopwatch();
    7. Stopwatch stopwatch2 = new Stopwatch();
    8. stopwatch.Start();
    9. for (int i = 0; i < 100000; i++)
    10. {
    11. stringBuilder1.Append(StringHelper.RegFilter(inputStr));
    12. }
    13. stopwatch.Stop();
    14. Console.WriteLine("正则方法过滤所用时间:"+stopwatch.ElapsedMilliseconds);
    15. stopwatch2.Start();
    16. for (int i = 0; i < 100000; i++)
    17. {
    18. stringBuilder2.Append(StringHelper.Filter(inputStr));
    19. }
    20. stopwatch2.Stop();
    21. Console.WriteLine("普通方法过滤所用时间:" + stopwatch2.ElapsedMilliseconds);
    22. Console.ReadKey();
    23. }



    三、执行结果:




    四、结论:

    正则的方式要快很多



    五、互助交流

    欢迎加入.net技术交流群.Net技术交流




  • 相关阅读:
    STL中的map
    HDU 4027 Can you answer these queries?
    HDU 2199 Can you solve this equation?
    USACO section1.2 Name That Number 命名那个数字
    HDU 3790 最短路径问题 (双重权值)
    [笔记]CiscoPT配置RIP
    [笔记]Cisco PT VLANTrunk配置
    iptables感悟Ubuntu
    CentOS网络配置
    Discuz X2 数据库备份功能分析
  • 原文地址:https://www.cnblogs.com/itmaxin/p/5cfa399e8f0c5f5348267c2c41e12677.html
Copyright © 2020-2023  润新知