C# 计算字符串中出现微笑的次数

C# 计算字符串中出现微笑的次数,c#,regex,string,C#,Regex,String,我正在创建一个计算字符串中出现的所有笑脸的方法。 我已经创建了另一个查询数据库以获取smiley字符串的方法 我希望此方法能够将:-:-检测为两个事件。以下是我尝试过的: public static int Occurrences(string input) { int count = 0; Smileys list = SmileyDAL.GetAll(); foreach (var item in list) { count += new

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

我希望此方法能够将:-:-检测为两个事件。以下是我尝试过的:

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;
} 
但调用此方法时出现以下错误:

解析;--太多了


您需要转义字符,替换:

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


您需要转义字符,替换:

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

必须对搜索字符串中的正则表达式字符进行转义


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

这里有另一个不使用正则表达式的选项

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;
} 

这里有另一个不使用正则表达式的选项

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;
} 

您的输入看起来怎么样?:-?try:-\请将您的常用表情添加到不同的笑脸中,或仅添加一个:-?例如是`;微笑?你的输入看起来怎么样?:-?try:-\请将您的常用表情添加到不同的笑脸中,或仅添加一个:-?例如是`;微笑?