【问题标题】:Replace emoticon with word in tweet using regex c#使用正则表达式 c# 用推文中的单词替换表情符号
【发布时间】:2011-12-21 11:02:36
【问题描述】:

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

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

【问题讨论】:

  • String.Replace 似乎是你的票。

标签: c# regex emoticons


【解决方案1】:

使用采用自定义匹配评估器的Regex.Replace 方法。

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

【讨论】:

  • 这就是我要找的。谢谢你。要添加 :D 我只需将正则表达式更改为 ":[()D]" 对吗?
  • @Vignesh 这是正确的。当然,您也需要扩展 ReplaceSmile 以接受 :D
【解决方案2】:

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

str = str.Replace(":(", "text1")
         .Replace(":)", "text2")
         .Replace(":D", "text3")

【讨论】:

  • 你可能有文字的地方:Dexter。其他两个没问题。
  • @Vignesh:任何方法(包括正则表达式)都会有这个问题。
  • 嗯,没错,但在 regex 中更容易在必要时添加更多条件。
【解决方案3】:

更通用的解决方案:

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

对于任何其他需要替换的表情符号,只需在字典中添加另一个键值对,例如 {":D", "laughing"}

作为 foreach 循环的替代方案,也可以(尽管不一定推荐)使用 Aggregate 标准查询运算符:

string result = emoticons.Aggregate(":) bla :(",
                (text, emoticon) => text.Replace(emoticon.Key, emoticon.Value));

【讨论】:

    【解决方案4】:

    为什么是正则表达式?

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

    【讨论】:

      猜你喜欢
      • 2020-01-06
      • 1970-01-01
      • 2018-09-29
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      相关资源
      最近更新 更多