Linell
Linell

Reputation: 749

Regex Filter in C#

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.

Upvotes: 3

Views: 1040

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726549

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>>.

Upvotes: 6

Related Questions