Вопрос

I have a problem with orderedDictionary and Regex. How can I define the problem by text but I'll try to explain...

This is my code:

var smilies = new OrderedDictionary
{
    {@":(", "smile_sadx24"},
    {@">:(", "smile_angryx24"},
};

foreach (string smiley in smilies.Keys)
{
    var re = new Regex(@"(?<!(=""))" + Regex.Escape(smiley) + @"(?<!(""))");
    if (re.IsMatch(incomingtext))
    {
        string m2 = re.Replace(incomingtext, "<img src=\"/Content/themes/mavi/img/custom/smiles/" + smilies[smiley] + ".png\"  alt=\"" + smiley + "\"/>");
        incomingtext = m2;
    }
}

When I tried to process >:( then it returned smile_sadx24 not smile_angryx24...

Because it catch :( firstly...

How can I solve this problem?

Это было полезно?

Решение

Two things:

var smilies = new OrderedDictionary
{
    {@">:(", "smile_angryx24"},  // Put this one first
    {@":(", "smile_sadx24"},
};

foreach (string smiley in smilies.Keys)
{
    var re = new Regex(@"(?<!(=""))" + Regex.Escape(smiley) + @"(?!(""))"); 
                       // Second should be a negative lookahead  ^^
    if (re.IsMatch(incomingtext))
    {
        string m2 = re.Replace(incomingtext, "<img src=\"/Content/themes/mavi/img/custom/smiles/" + smilies[smiley] + ".png\"  alt=\"" + smiley + "\"/>");
        incomingtext = m2;
    }
}

ideone demo

Using a negative look behind where there was supposed to be a lookahead was what caused the regex to fail when you swapped the angry and sad smileys, because the smiley characters aren't using " at all.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top