西西軟件園多重安全檢測(cè)下載網(wǎng)站、值得信賴的軟件下載站!
軟件
軟件
文章
搜索

首頁(yè)編程開(kāi)發(fā)其它知識(shí) → 文章中的特殊詞語(yǔ)使用正則替換屏蔽

文章中的特殊詞語(yǔ)使用正則替換屏蔽

相關(guān)軟件相關(guān)文章發(fā)表評(píng)論 來(lái)源:西西整理時(shí)間:2011/5/10 14:03:17字體大。A-A+

作者:西西點(diǎn)擊:81次評(píng)論:2次標(biāo)簽: 正則

  • 類(lèi)型:電子教程大。9.5M語(yǔ)言:中文 評(píng)分:8.0
  • 標(biāo)簽:
立即下載

使用正則替換文章屏蔽詞,1500個(gè)屏蔽詞,6KB的文章,替換用時(shí)1毫秒
使用正則替換文章屏蔽詞,這個(gè)功能很早就用到了,由于使用過(guò)程中并未感覺(jué)到什么壓力,所以一直沒(méi)有對(duì)其性能進(jìn)行優(yōu)化。

今天應(yīng)leader要求,對(duì)性能進(jìn)行了一下測(cè)試并作出改進(jìn),發(fā)現(xiàn)改進(jìn)后的性能提高了100多倍!原來(lái)替換一篇文章用時(shí)130多毫秒,現(xiàn)在只需要不到1毫秒的時(shí)間!

前后主要差別在于正則的生成和循環(huán)文章內(nèi)容的次數(shù)。

下邊貼出主要代碼供大家參考。

view sourceprint?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]+$", 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>

/// 檢查輸入內(nèi)容是否包含臟詞(包含返回true)

/// </summary>

public static bool HasBlockWords(string raw)

{

return GetRegex().Match(raw).Success;

}

/// <summary>

/// 臟詞替換成*號(hào)

/// </summary>

public static string WordsFilter(string raw)

{

return GetRegex().Replace(raw, "***");

}

/// <summary>

/// 獲取內(nèi)容中含有的臟詞

/// </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[]{"國(guó)民黨","fuck","110"};//這里應(yīng)該從數(shù)據(jù)庫(kù)獲取

}

這個(gè)程序可替換以下內(nèi)容:

國(guó)民黨

國(guó)-民-黨

國(guó)o民o黨

fuck

f.u.c.k

110(110的變形寫(xiě)法不被替換)

    相關(guān)評(píng)論

    閱讀本文后您有什么感想? 已有人給出評(píng)價(jià)!

    • 8 喜歡喜歡
    • 3 頂
    • 1 難過(guò)難過(guò)
    • 5 囧
    • 3 圍觀圍觀
    • 2 無(wú)聊無(wú)聊

    熱門(mén)評(píng)論

    最新評(píng)論

    發(fā)表評(píng)論 查看所有評(píng)論(2)

    昵稱:
    表情: 高興 可 汗 我不要 害羞 好 下下下 送花 屎 親親
    字?jǐn)?shù): 0/500 (您的評(píng)論需要經(jīng)過(guò)審核才能顯示)