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


功能:使用正則  對玩家昵稱處理,如果含有 屏蔽字庫里的敏感字眼進行屏蔽。已封裝成dll

 

1.屏蔽字庫處理成所需要的正則格式:(所需正則表達式格式:".*((XX)|(XX)|(XX)|....).*")

 

2.FilterHelper類中:

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM