我有像这样的数据库中的表情符号列表
id | emoticon | convert_text
1 | :) | e_happy
2 | :( | e_sad
等
如何检查表情符号列表中是否包含任何字符?
如果找到,则将表情符号更改为文本。
示例:
before
S = Smile at everyone who doesn't smile at your :)
after
S= Smile at everyone who doesn't smile at your e_happy
*被修改
首先,我试图像这样分开每个单词
static void Main(string[] args)
{
string value = "Smile at everyone who doesn't smile at your :)";
char[] delimiter = new char[] { ' ', ',', '.' };
string[] array = value.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
foreach (string entry in array)
{
Console.WriteLine(entry);
}
Console.ReadKey();
}
我很困惑如何用数据库中的表情符号列表检查每个单词,并将表情符号转换为文本,例如示例 *对不起,这是我的第一篇文章,我正在翻译谷歌翻译
答案 0 :(得分:1)
由于表情符号的数量和符号可能非常大且非常随机( like :) ;) >:) @}-, etc; and then new can be added anytime
),我认为正则表达式不能用于所有表情符号。所以我想以更冗长的方式解决这个问题。
声明字典
Dictionary<string, string> emoticons = new Dictionary<string, string>();
将表情符号加载到字典中(使用DataReader)
// declare/open the connection (depends on the current application design
string sql = "SELECT * FROM Emoticons
// cmd.ExecuteReader above query to get dataReader (dr)
while(dr.Read())
{
string key = dr.GetString(dr.GetOrdinal("Emoticons"));
if(!emoticons.ContainsKey(key))
emoticons.Add(key, dr.GetString(dr.GetOrdinal("convert_test"));
}
dr.Close();
上面的字典可以存储为类级别对象或项目级别的全局对象,这样您就不必每次都读取数据库。
用convert_text替换所有表情符号
foreach(string key in emoticons.Keys)
value = value.Replace(key, emoticons[key]);
// here you will have all emoticons converted with their convert_text.
答案 1 :(得分:0)
如何使用正则表达式?
var emoticons = new Dictionary<string, string>
{
{ ":)" , "smile" },
{ ";)" , "blink" },
{ ">:)", "devil" },
{ "@}-", "rose" }
};
string value = "Smile at everyone who doesn't smile at your :)";
Console.WriteLine(Regex.Replace(value,
String.Join("|",emoticons.Select(e => Regex.Escape(e.Key)).ToArray()),
(match) =>
{
string result = null;
return emoticons.TryGetValue(match.Value, out result)
? result : match.Value;
}));
使用正则表达式,如果已经将它们正确地转义到数据库中,则可以使用相同的表达式匹配:)
或:]
。在此示例中,我认为所有表达式都是“不安全的”,因此我使用Regex.Escape
调用