C# 使用正则表达式c将tweet中的表情符号替换为单词#

C# 使用正则表达式c将tweet中的表情符号替换为单词#,c#,regex,emoticons,C#,Regex,Emoticons,基本上,这个想法是将字符串中的表情符号映射到实际单词。你用快乐代替它。 一个更清楚的例子是。 原件: 今天是一个阳光明媚的日子:)。但是明天就要下雨了。 最终: 今天是一个阳光明媚的日子,心情愉快,但明天就要下雨了 我正在尝试一种解决方案,对所有表情符号使用一个通用正则表达式,但我不确定一旦你检测到它是一个表情符号,如何返回并用适当的单词替换每个表情符号。 我只需要三个表情符号:),:(和:D。谢谢。为什么不使用普通的替换?您只有三个固定的模式: str = str.Replace(":(",

基本上,这个想法是将字符串中的表情符号映射到实际单词。你用快乐代替它。 一个更清楚的例子是。 原件: 今天是一个阳光明媚的日子:)。但是明天就要下雨了。 最终: 今天是一个阳光明媚的日子,心情愉快,但明天就要下雨了

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

为什么不使用普通的替换?您只有三个固定的模式:

str = str.Replace(":(", "text1")
         .Replace(":)", "text2")
         .Replace(":D", "text3")
使用接受自定义匹配计算器的方法

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 + "]");
}
为什么是正则表达式

 string newTweet = oldTweet
  .Replace(":)","happy")
  .Replace(":(","sad")
  .Replace(":D","even more happy");

一个更普遍的解决方案:

var emoticons = new Dictionary<string, string>{ {":)", "happy"}, {":(", "sad"} };
string result = ":) bla :(";
foreach (var emoticon in emoticons)
{
    result = result.Replace(emoticon.Key, emoticon.Value);
}

String.Replace似乎是您的票。这是我一直在寻找的。谢谢您添加:D我只是将正则表达式更改为“:[()D]”对吗?@Vignesh这是正确的。当然,你也需要扩展
ReplaceSmile
来接受
:D
。一些你可能有文本的地方:Dexter。对于其他两个,这是很好的。@Vignesh:任何方法(包括regex)都会有这个问题.hmm这是真的,但在正则表达式中,在必要时添加更多条件更容易。
string result = emoticons.Aggregate(":) bla :(",
                (text, emoticon) => text.Replace(emoticon.Key, emoticon.Value));