3

I'm creating a sort of filter for a message, but running into some trouble with actually replacing parts of the word.

After looking over this question, I tried to do it almost exactly like they did. However, I want to work with multiple possible words to filter, and I want each to have a different thing to change to. A dictionary would seem to work perfectly for this. However, it does not work.

        Dictionary<string, string> filterWords = new Dictionary<string, string>
        {
            {"lol", "LAUGH OUT LOUD"},
            {"wtf", "WOW THAT'S FANTASTIC"},
        };

        foreach (KeyValuePair<string, string> word in filterWords)
        {
            Regex r = new Regex(@"\b" + word.Key + "\b");
            message = r.Replace(message, word.Value);
        }

I don't see anything really wrong with the code, but it doesn't actually replace any words, and I'm stumped as to how to fix it.

Community
  • 1
  • 1
Linell
  • 750
  • 3
  • 9
  • 27

1 Answers1

6

The two problems that I see with this code is that it treats message case-sensitively, and that you missed the @ in front of the second "\b" literal, making "\b" a backspace, not an end-of-word marker.

Try replacing

Regex r = new Regex(@"\b" + word.Key + "\b");

with

Regex r = new Regex(@"\b" + word.Key + @"\b", RegexOptions.IgnoreCase);

the rest of your code should work fine.

You may want to optimize your code a little by per-compiling your regexes. In addition, since filterWords is not really a Dictionary, you may want to use List<Tuple<Regex,string>>.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Usually, you are lucky when you forget to escape a character and get the unkown escape sequence compilation error, but if you choose one of these: http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-character-escape-sequences-are-available.aspx, it will compile just fine – Gray Jul 11 '13 at 19:29
  • 1
    `@"\\b"` and `"\\b"` are different, corresponding to `\\b` and `\b` respectively. I think you want `@"\b"` or `"\\b"`, which parse to `\b`, which parses to regex's word boundary. – Tim S. Jul 11 '13 at 19:30