正則置換文章遮蔽語,1500個遮蔽語,6 KBの文章を用い,置換時間01ミリ秒

3028 ワード

文章のシールドを正則的に置き換える機能は古くから使われており、使用中にストレスを感じないため、性能を最適化していない.
今日はリーダーの要求に応じて、性能をテストして改善して、改善した後の性能が100倍以上向上したことを発見しました!文章を置き換えるのに130ミリ秒以上かかりましたが、今は1ミリ秒未満の時間しかかかりません.
前後の主な違いは,正則の生成と文章内容のループの回数にある.
下に主なコードを貼って参考にしてください.
        private static readonly Regex reg_b = new Regex(@"/B", RegexOptions.Compiled);
        private static readonly Regex reg_en = new Regex(@"[a-zA-Z]+", RegexOptions.Compiled);
        private static readonly Regex reg_num = new Regex(@"^[/-/./s/d]+{1}quot;, RegexOptions.Compiled);

        private static Regex reg_word = null; //          

        private static Regex GetRegex()
        {
            if (reg_word == null)
            {
                reg_word = new Regex(GetPattern(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
            }
            return reg_word;
        }

        /// <summary>
        ///             (    true)
        /// </summary>
        public static bool HasBlockWords(string raw)
        {
            return GetRegex().Match(raw).Success;
        }
        /// <summary>
        ///      * 
        /// </summary>
        public static string WordsFilter(string raw)
        {
            return GetRegex().Replace(raw, "***");
        }
        /// <summary>
        ///           
        /// </summary>
        public static IEnumerable<string> GetBlockWords(string raw)
        {
            foreach (Match mat in reg_word.Matches(raw))
            {
                yield return (mat.Value);
            }
        }
        private static string GetPattern()
        {
            StringBuilder patt = new StringBuilder();
            string s;
            foreach (string word in GetBlockWords())
            {
                if (word.Length == 0) continue;
                if (word.Length == 1)
                {
                    patt.AppendFormat("|({0})", word);
                }
                else if (reg_num.IsMatch(word))
                {
                    patt.AppendFormat("|({0})", word);
                }
                else if (reg_en.IsMatch(word))
                {
                    s = reg_b.Replace(word, @"(?:[^a-zA-Z]{0,3})");
                    patt.AppendFormat("|({0})", s);
                }
                else
                {
                    s = reg_b.Replace(word, @"(?:[^/u4e00-/u9fa5]{0,3})");
                    patt.AppendFormat("|({0})", s);
                }
            }
            if (patt.Length > 0)
            {
                patt.Remove(0, 1);
            }
            return patt.ToString();
        }

        /// <summary>
        ///       
        /// </summary>
        public static string[] GetBlockWords()
        {
            return new string[]{"   ","fuck","110"};//          
        }

このプログラムは次の内容に置き換えられます.
fuck
f.u.c.k
110(110の変形表記は置き換えられない)