【问题标题】:OrderedDictionary and Regex有序字典和正则表达式
【发布时间】:2014-02-08 00:42:44
【问题描述】:

我对@9​​87654321@ 和Regex 有疑问。我如何通过文字来定义问题,但我会尝试解释......

这是我的代码:

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

当我尝试处理 &gt;:( 时,它返回 smile_sadx24 而不是 smile_angryx24...

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

我该如何解决这个问题?

【问题讨论】:

  • 试试把愤怒的笑脸放在字典的首位?
  • 已经试过了。没有效果:/

标签: c# regex ordereddictionary


【解决方案1】:

两件事:

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

在应该向前看的地方在使用负面的外观是导致正则表达式在您交换愤怒和悲伤的笑脸时失败的原因,因为笑脸字符没有使用"完全没有。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-14
    • 2016-04-28
    • 2012-06-11
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多