c# - 如何从字符串内容中删除一些特殊的单词?

标签 c# string-formatting

我有一些包含表情符号图标代码的字符串,例如 :grinning::kissing_heart::bouquet:。我想处理它们以删除表情符号代码。

例如,给定:

Hello:grinning: , how are you?:kissing_heart: Are you fine?:bouquet:

我想得到这个:

Hello , how are you? Are you fine?

我知道我可以使用这段代码:

richTextBox2.Text = richTextBox1.Text.Replace(":kissing_heart:", "").Replace(":bouquet:", "").Replace(":grinning:", "").ToString();

但是,我必须删除 856 个不同的表情符号图标(使用此方法,需要调用 856 次 Replace())。有没有其他方法可以做到这一点?

最佳答案

您可以使用 Regex 来匹配 :anything: 之间的单词。将 Replace 与函数一起使用,您可以进行其他验证。

string pattern = @":(.*?):";
string input = "Hello:grinning: , how are you?:kissing_heart: Are you fine?:bouquet: Are you super fan, for example. :words not to replace:";
string output = Regex.Replace(input, pattern, (m) =>
{
    if (m.ToString().Split(' ').Count() > 1) // more than 1 word and other validations that will help preventing parsing the user text
    {
        return m.ToString();
    }
    return String.Empty;
}); // "Hello , how are you? Are you fine? Are you super fan, for example. :words not to replace:"

如果您不想使用利用 lambda 表达式的 Replace,您可以使用 \w,正如@yorye-nathan 提到的那样,只匹配话。

string pattern = @":(\w*):";
string input = "Hello:grinning: , how are you?:kissing_heart: Are you fine?:bouquet: Are you super fan, for example. :words not to replace:";
string output = Regex.Replace(input, pattern, String.Empty); // "Hello , how are you? Are you fine? Are you super fan, for example. :words not to replace:"

关于c# - 如何从字符串内容中删除一些特殊的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30450170/

相关文章:

c# - 验证用户输入

c# - 如何正确格式化字符串?

rust - 如何在 Rust 中将字节格式化为 2 位十六进制字符串

c# - 有什么简单的方法可以将数据导出为多种格式吗?

c# - INotifyPropertyChanged 不会通过 View 模型

c# - EF 上下文的大小

c# - SQL Server中的存储过程;语法错误

c# - EntityFramework 拒绝忘记旧列

java在2个小数位后剪切字符串?

java - String.format() 是大写参数