Skip to main content
 首页 » 编程设计

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

2024年02月23日29shanyou

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

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

请您参考如下方法:

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