OrderedDictionary和Regex

OrderedDictionary和Regex

我在orderedDictionaryRegex上有问题。如何通过文字定义问题,但我会尽力解释...

这是我的代码:

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


当我尝试处理>:(时,它返回了smile_sadx24而不是smile_angryx24 ...

因为它首先捕获:( ...

我怎么解决这个问题?

最佳答案

两件事情:

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

在交换生气和悲伤的笑脸时,在应该进行前瞻的后面使用否定外观会导致正则表达式失败,因为笑脸字符根本没有使用"

10-07 13:29