Replace Bad words using Regex

后端 未结 4 1392
小蘑菇
小蘑菇 2021-01-11 14:32

I am trying to create a bad word filter method that I can call before every insert and update to check the string for any bad words and replace with \"[Censored]\".

4条回答
  •  走了就别回头了
    2021-01-11 15:24

    Although I'm a big fan of Regex, I think it won't help you here. You should fetch your bad word into a string List or string Array and use System.String.Replace on your incoming message.

    Maybe better, use System.String.Split and .Join methods:

    string mayContainBadWords = "... bla bla ...";
    string[] badWords = new string[]{"bad", "worse", "worst"};
    
    string[] temp = string.Split(badWords, StringSplitOptions.RemoveEmptyEntries);
    string cleanString = string.Join("[Censored]", temp);
    

    In the sample, mayContainBadWords is the string you want to check; badWords is a string array, you load from your bad word sql table and cleanString is your result.

提交回复
热议问题