过滤坏词和故意拼写错误的单词的所有排列?

时间:2013-08-19 22:20:43

标签: c# regex

使用正则表达式从文本块中过滤诅咒词有什么好方法?

我不想取代经典中的“屁股”(一个克隆错误),所以它需要能够通过单词边界来实现。

此外,它需要捕获排列,如l33tpeak,单词中的空格等。它不一定是完美的(进入的系统也将具有消息标记功能)但它应该得到人们可能会使用的大部分诅咒。

PG13示例:如果试图阻止“潮湿”这个词,它应该能够匹配“潮湿”以及“m01st”,“MOIST”,“m0ist”并希望“m oist”。

1 个答案:

答案 0 :(得分:3)

根据@Unknwntech提供的答案,这是一个等同于位于"bad words" filter的封闭线程的C#:

    public string ReplaceBadWords(string data, string[] badWords, out int badWordCount)
    {
        int count = 0;
        Regex r;
        string op = data;
        foreach (var word in badWords)
        {
            var expword = ExpandBadWordToIncludeIntentionalMisspellings(word);
            r = new Regex(@"(?<Pre>\s+)(?<Word>" + expword + @")(?<Post>\s+|\!\?|\.)");
            var matches = r.Matches(data);
            foreach (Match match in matches)
            {
                string pre = match.Groups["Pre"].Value;
                string post = match.Groups["Post"].Value;
                string output = pre + new string('*', word.Length) + post;
                op = op.Replace(match.Value, output);
                count++;
            }
        }
        badWordCount = count;
        return op;
    }

    public string ExpandBadWordToIncludeIntentionalMisspellings(string word)
    {
        var chars = word
            .ToCharArray();

        var op = "[" + string.Join("][", chars) + "]";

        return op   
            .Replace("[a]", "[a A @]")
            .Replace("[b]", "[b B I3 l3 i3]")
            .Replace("[c]", "(?:[c C \\(]|[k K])")
            .Replace("[d]", "[d D]")
            .Replace("[e]", "[e E 3]")
            .Replace("[f]", "(?:[f F]|[ph pH Ph PH])")
            .Replace("[g]", "[g G 6]")
            .Replace("[h]", "[h H]")
            .Replace("[i]", "[i I l ! 1]")
            .Replace("[j]", "[j J]")
            .Replace("[k]", "(?:[c C \\(]|[k K])")
            .Replace("[l]", "[l L 1 ! i]")
            .Replace("[m]", "[m M]")
            .Replace("[n]", "[n N]")
            .Replace("[o]", "[o O 0]")
            .Replace("[p]", "[p P]")
            .Replace("[q]", "[q Q 9]")
            .Replace("[r]", "[r R]")
            .Replace("[s]", "[s S $ 5]")
            .Replace("[t]", "[t T 7]")
            .Replace("[u]", "[u U v V]")
            .Replace("[v]", "[v V u U]")
            .Replace("[w]", "[w W vv VV]")
            .Replace("[x]", "[x X]")
            .Replace("[y]", "[y Y]")
            .Replace("[z]", "[z Z 2]")
            ;
    }

只要您有一个好的错误单词列表,这在预防垃圾错误方面做得相当不错(是的,谷歌)。