码迷,mamicode.com
首页 > 其他好文 > 详细

C# 玩家昵称屏蔽敏感字眼

时间:2014-07-16 23:02:50      阅读:319      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   os   

功能:使用正则  对玩家昵称处理,如果含有 屏蔽字库里的敏感字眼进行屏蔽。已封装成dll

 

1.屏蔽字库处理成所需要的正则格式:(所需正则表达式格式:".*((XX)|(XX)|(XX)|....).*")

bubuko.com,布布扣

 

2.FilterHelper类中:

bubuko.com,布布扣
public sealed class FilterHelper
    {
        private Regex r;

        #region Singleton
        private static readonly FilterHelper instance = new FilterHelper();
        public static FilterHelper Instance { get { return instance; } }
        private FilterHelper() { }
        #endregion

        private void ReadRex()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            string textFile = path + "FilterSt.txt";
            FileStream fs;
            if (File.Exists(textFile))
            {
                fs = new FileStream(textFile, FileMode.Open, FileAccess.Read);
                using (fs)
                {
                    ////TextRange text = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd);
                    //text.Load(fs, DataFormats.Text);

                    //创建一个容量4M的数组
                    byte[] byteData = new byte[fs.Length];
                    //从文件中读取数据写入到数组中(数组对象,从第几个开始读,读多少个)
                    //返回读取的文件内容真实字节数
                    int length = fs.Read(byteData, 0, byteData.Length);
                    //如果字节数大于0,则转码
                    if (length > 0)
                    {
                        //将数组转以UTF-8字符集编码格式的字符串
                        var filterst = ".*(" + Encoding.UTF8.GetString(byteData) + ").*";
                        r=new Regex(@filterst);
                    }

                }
            }
            else
            {
                throw new FileNotFoundException("找不到屏蔽字库");
            }
        }

        /// <summary>
        /// 判断是否屏蔽
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool IsStFilter(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                throw new Exception("输入不能为空");
            }
            if (r == null)
            {
                ReadRex();
            }

            if (r.IsMatch(input))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
View Code

 

3.需要判断是否屏蔽的地方:直接调用FilterHelper.Instance.IsStFilter(判断的昵称)

 

备注:1、dll中只能包含代码,资源文件必须复制到对应的输出路径。

   2、屏蔽字库的txt要复制到项目的输出路径,也就是 AppDomain.CurrentDomain.BaseDirectory说对应的路径。

 

Demo连接:http://download.csdn.net/detail/ofat___lin/7615715

 

C# 玩家昵称屏蔽敏感字眼,布布扣,bubuko.com

C# 玩家昵称屏蔽敏感字眼

标签:style   blog   http   color   使用   os   

原文地址:http://www.cnblogs.com/fatlin/p/3835402.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!