计算字符串中表情符号的出现次数

时间:2013-01-15 13:12:30

标签: c# regex string

我正在创建一个方法来计算字符串中出现的所有表情符号。 (我已经创建了另一种查询数据库以获取笑脸字符串的方法。)

我希望这种方法能够将:-):-)检测为两次出现。这是我尝试过的:

public static int Occurrences(string input)
{
    int count = 0;

    Smileys list = SmileyDAL.GetAll();

    foreach (var item in list)
    {
        count += new Regex(item.Key).Matches(input).Count;

    }

    return count;
} 

但是在调用此方法时我收到此错误:

  

解析“;-)” - 太多了)。

3 个答案:

答案 0 :(得分:4)

您需要转义)字符,替换:

count += new Regex(item.Key).Matches(input).Count;

使用:

count += new Regex(Regex.Escape(item.Key)).Matches(input).Count;

答案 1 :(得分:2)

new Regex(Regex.Escape(item.Key))

您必须转义搜索字符串中的正则表达式字符。

答案 2 :(得分:0)

这是另一种不使用正则表达式的选项

public static int Occurences(string input)
{
    // Put all smileys into an array.
    var smileys = SmileyDAL.GetAll().Select(x => x.Key).ToArray();

    // Split the string on each smiley.
    var split = input.Split(smileys, StringSplitOptions.None);

    // The number of occurences equals the length less 1.
    return split.Length - 1;
}