基本上,这个想法是将字符串中的表情符号映射到实际单词。说:)你用快乐代替它。一个更清楚的例子是。原文:今天是晴天:)。但是明天会下雨:(。决赛:今天是个阳光明媚的日子,很开心。但明天会下雨,很伤心。
我已经尝试了一个对所有表情符号使用通用正则表达式的解决方案,但我不确定一旦你检测到它是一个表情符号,如何返回并用适当的单词替换每个表情符号。我只需要三个表情符号:)、:(和:D。谢谢。
为什么不使用普通替换?您只有三个固定模式:
str = str.Replace(":(", "text1")
.Replace(":)", "text2")
.Replace(":D", "text3")
使用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 + "]");
}
更通用的解决方案:
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));
为什么是正则表达式?
string newTweet = oldTweet
.Replace(":)","happy")
.Replace(":(","sad")
.Replace(":D","even more happy");