使用Regex替换坏词

Mar*_*iff 11 .net c# regex

我试图创建一个坏的过滤器方法,我可以在每次插入和更新之前调用,以检查字符串是否有任何坏词并替换为"[Censored]".

我有一个SQL表,有一个坏词列表,我想把它们带回来,并将它们添加到List或字符串数​​组,并检查传入的文本字符串,如果找到任何坏词替换它们和返回一个过滤后的字符串.

我正在使用C#.

Tim*_*oyd 18

在进行字符串替换之前,请查看此"clbuttic"(或针对您的案例cl [Censored] ic)文章,而不考虑单词边界:

http://www.codinghorror.com/blog/2008/10/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea.html

更新

显然不是万无一失(参见上面的文章 - 这种方法很容易解决或产生误报......)或优化(正则表达式应该被缓存和编译),但以下将过滤掉整个单词(没有"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);
Run Code Online (Sandbox Code Playgroud)

给出输出:

对于[截尾] [截尾]日,我没有[截尾]睡眠 - 隔壁邻居正在全速演奏古典音乐!

请注意,"经典"不会变成"cl [Censored] ical",因为整个单词与正则表达式匹配.

更新2

并且为了演示如何(以及通常基本的字符串\模式匹配技术)可以轻易破坏的风格,请参阅以下字符串:

"我已经没有为chuffıngchuffıngs天睡觉了 - 隔壁邻居正在全速演奏古典音乐!"

我用"土耳其小写"取代了"我",取消了"ı".仍然看起来非常冒犯!