且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用正则表达式C#用推文中的单词替换表情符号

更新时间:2023-02-22 13:53:30

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