Search code examples
c#regexemoticons

Replace emoticon with word in tweet using regex c#


Basically the idea is to map the emoticons in the string to actual words. say for :) you replace it with happy. A more clear example would be. Original: Today is a sunny day :). But tomorrow it is going to rain :(. Final: Today is a sunny day happy. But tomorrow it is going to rain sad.

I have trying a solution using a common regex for all emoticons but I am not sure once you detect it is an emoticon, how to go back and replace each one with appropriate word. I need it only for three emoticons :),:( and :D. Thank you.


Solution

  • Use Regex.Replace method that takes a custom match evaluator.

    static string ReplaceSmile(Match m) {
        string x = m.ToString();
        if (x.Equals(":)")) {
            return "happy";
        } else if (x.Equals(":(")) {
            return "sad";
        }
        return x;
    }
    
    static void Main() {
        string text = "Today is a sunny day :). But tomorrow it is going to rain :(";
        Regex rx = new Regex(@":[()]");
        string result = rx.Replace(text, new MatchEvaluator(ReplaceSmile));
        System.Console.WriteLine("result=[" + result + "]");
    }