使用正则表达式C#用推文中的单词替换表情符号 [英] Replace emoticon with word in tweet using regex c#

查看:275
本文介绍了使用正则表达式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.

我正在尝试对所有表情使用通用正则表达式的解决方案,但我不确定一旦检测到它是表情,如何返回并用适当的单词替换每个表情. 我只需要三个表情符号:),:(和:D.谢谢.

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.

推荐答案

使用 Regex.Replace 方法,该方法具有自定义匹配评估程序.

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 + "]");
}

这篇关于使用正则表达式C#用推文中的单词替换表情符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆