zoukankan      html  css  js  c++  java
  • 两种模糊过滤关键字的方法

    要过滤特定内容的关键字,如果是精确过滤很好办,直接Replace就能搞定,但一些单词却会因大小写的问题可能不会被过滤,先看一个例子:

    有以下内容:

    Two birds in the tree, They are talking happily,
    what they are talking about,they are talking family.

    现在如果我想要过滤掉所有的"they",要全部替换成"它们",

    如果用Replace的话,只能替换一种情况,即全字匹配"they"。

    但文中的"They"就不能被过滤,所以还是要以一种特殊的方法来实现。

    我用了两个方法来实现关键字的模糊过滤:

    方法一:

    这个方法比较简单,就是进行内容的遍历来匹配过滤的字符,代码如下:

      /// <summary>
      /// 过滤关键字
      /// </summary>
      /// <param name="strContent">待过滤的内容。</param>
      /// <param name="strKeyWord">要过滤的关键字。</param>
      /// <param name="strNewString">要过滤的关键字的替换字符串。</param>
      /// <returns>返回检查后的内容。</returns>
      private string FilterKeyWord(string strContent,string strKeyWord,string strNewString)
      {
       for(int i=0;i<=(strContent.Length-strKeyWord.Length);i++)
       {
        // 找到匹配顶。
        if(strContent.Substring(i,strKeyWord.Length).ToUpper()==strKeyWord.ToUpper())
        {
         strContent=strContent.Substring(0,i)+strNewString+strContent.Substring(i+strKeyWord.Length);
        }
       }
       return strContent;
      }

    该方法将会用指定的新字符串替换掉内容中的指定关键字。
    虽然可以实现关键字的过滤,但因为要遍历一遍,所以效率不是很高。


    再来看第二种方法:

      /// <summary>
      /// 过滤关键字
      /// </summary>
      /// <param name="strContent">待过滤的内容。</param>
      /// <param name="strKeyWord">要过滤的关键字。</param>
      /// <param name="strNewString">要过滤的关键字的替换字符串。</param>
      /// <returns>返回过滤后的内容。</returns>
      public static StringBuilder FilterKeyWord(StringBuilder strContent,string strKeyWord,string strNewString)
      {
       string ExpressionString=null;
       // 创建要构造正则表达式的字符串。
       for(int i=0;i<strKeyWord.Length;i++)
       {
        ExpressionString+="("+strKeyWord.Substring(i,1).ToUpper()+"|"+strKeyWord.Substring(i,1).ToLower()+")";
       }

       // 构造要匹配的正则表达式。
       Regex Expression=new Regex(ExpressionString);

       // 在要过滤的内容中查寻匹配。
       Match match=Expression.Match(strContent.ToString(),0,strContent.Length);
       
       // 替换匹配的内容,直到匹配失败。
       while(match.Success)
       {
        // 替换当前匹配的内容。
        strContent=strContent.Replace(match.Value,strNewString);

        // 继续查寻下一次的匹配。
        match=match.NextMatch();
       }
       return strContent;
      }

    这是用正则表达式来进行匹配,效率相对而言要高了一点点。

    而且用了StringBuilder类,在内存空间上要占用得相对少一些。


     

  • 相关阅读:
    VisualStudio2010配置OpenCV的一种一劳永逸的方法
    QT5 Failed to load platform plugin &quot;windows&quot; 终极解决方式 命令行问题
    轻松学习JavaScript二十二:DOM编程学习之节点操作
    Eclipse中安装TestNG插件
    Java Timer 定时器的使用
    技术开发团队的项目管理工具
    python里一个class可以定义多个构造函数
    python中的多继承
    python基础之使用os.system来执行系统命令
    python下划线变量的含义
  • 原文地址:https://www.cnblogs.com/Random/p/739696.html
Copyright © 2011-2022 走看看