gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:36:02 26 4
gpt4 key购买 nike

我有一些包含表情符号图标代码的字符串,例如 :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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com