[英]Replace Bad words using Regex
我試圖創建一個壞的過濾器方法,我可以在每次插入和更新之前調用,以檢查字符串是否有任何壞詞並替換為“[Censored]”。
我有一個SQL表,有一個壞詞列表,我想把它們帶回來,並將它們添加到List或字符串數組,並檢查傳入的文本字符串,如果找到任何壞詞替換它們和返回一個過濾后的字符串。
我正在使用C#。
在進行字符串替換之前,請查看此“clbuttic”(或針對您的案例cl [Censored] ic)文章,而不考慮單詞邊界:
更新
顯然不是萬無一失(參見上面的文章 - 這種方法很容易解決或產生誤報......)或優化(正則表達式應該被緩存和編譯),但以下將過濾掉整個單詞(沒有“clbuttics” )和簡單的復數詞:
const string CensoredText = "[Censored]";
const string PatternTemplate = @"\b({0})(s?)\b";
const RegexOptions Options = RegexOptions.IgnoreCase;
string[] badWords = new[] { "cranberrying", "chuffing", "ass" };
IEnumerable<Regex> badWordMatchers = badWords.
Select(x => new Regex(string.Format(PatternTemplate, x), Options));
string input = "I've had no cranberrying sleep for chuffing chuffings days -
the next door neighbour is playing classical music at full tilt!";
string output = badWordMatchers.
Aggregate(input, (current, matcher) => matcher.Replace(current, CensoredText));
Console.WriteLine(output);
給出輸出:
對於[截尾] [截尾]日,我沒有[截尾]睡眠 - 隔壁鄰居正在全速演奏古典音樂!
請注意,“經典”不會變成“cl [Censored] ical”,因為整個單詞與正則表達式匹配。
更新2
並且為了演示如何(以及通常基本的字符串\\模式匹配技術)可以輕易破壞的風格,請參閱以下字符串:
“我已經沒有為chuffıngchuffıngs天睡覺了 - 隔壁鄰居正在全速演奏古典音樂!”
我用“土耳其小寫”取代了“我”,取消了“ı”。 仍然看起來非常冒犯!
雖然我是Regex的忠實粉絲,但我認為這對你沒有幫助。 您應該將您的壞詞提取到字符串List或string Array中,並在傳入消息上使用System.String.Replace
。
也許更好,使用System.String.Split
和.Join
方法:
string mayContainBadWords = "... bla bla ...";
string[] badWords = new string[]{"bad", "worse", "worst"};
string[] temp = string.Split(badWords, StringSplitOptions.RemoveEmptyEntries);
string cleanString = string.Join("[Censored]", temp);
在示例中, mayContainBadWords
是您要檢查的字符串; badWords
是一個字符串數組,你從壞詞sql表加載, cleanString
是你的結果。
您可以使用string.replace()方法或RegEx類
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.