1

文字列内のスマイリーのすべての出現をカウントするメソッドを作成しています。(データベースにクエリを実行してスマイリー文字列を取得する別のメソッドを既に作成しています。)

:-):-)このメソッドが2 つのオカレンスとして検出できるようにしたいと考えています。これが私が試したことです:

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

しかし、このメソッドを呼び出すと、次のエラーが発生します。

解析 ";-)" - ) が多すぎます。

4

3 に答える 3

4

文字をエスケープして)、次を置き換える必要があります。

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

と:

count += new Regex(Regex.Escape(item.Key)).Matches(input).Count;
于 2013-01-15T13:15:01.800 に答える
2
new Regex(Regex.Escape(item.Key))

検索文字列の正規表現文字をエスケープする必要があります。

于 2013-01-15T13:15:50.423 に答える
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;
} 
于 2013-01-15T13:21:37.530 に答える