I'm adding a profanity filter and what I would like to do is replace the word (or partial word) that's replaced with a string of equal length. The equal length part is where I'm having difficulty.
So if the word being replaced is 3 characters long than I want the text it's replaced with to be 3 characters long. I'm not sure how I can substring my replacement string to match the length of the word being replaced.
Here's my test method:
public static string ProfanityFilter(this string text)
{
string pattern = @"\bword\b|\bword2\b|\banother*";
Regex regex = new Regex(pattern);
string replacement = "*%$@^!#@!@$^()!";
return regex.Replace(text, replacement);
}
So, if the word "another" is replaced, it would be replaced with "*%$@^!#".
If "word" is replaced it would be replaced with "*%$@^"
If "wording" is replaced it would be replaced with "*%$@^ing"
Update:
I ended up finding the solution...
I created a new method:
public static string Censored(Match match)
{
string replacement = "*%$@^!#@!@$^()!";
return replacement.Substring(0, match.Captures[0].Length);
}
Then changed
return regex.Replace(text, replacement);
to
return regex.Replace(text, Censored);
Substring, will throw an exception if the capture length exceeds the replacement string's length. A safer way would be to build up the replacement string from a set of different characters if you really want it to consist of all those different characters. Otherwise you can specify one character and build it up with theStringconstructor as I've shown in my answer.