为什么这个正则表达式插入标签?

时间:2013-05-01 14:49:20

标签: c# regex

我从MSSQL CLR调用了以下函数:

private static string ReplaceTags(string input, string TagsReplacementXML)
{
    const string TagNamePattern = @"<\$\w+>";
    const string ReplacementPattern = @"<\${0}\>";

    XDocument doc = XDocument.Parse(TagsReplacementXML);
    var xmltags = doc.Descendants("Tag").Select(x => new KeyValuePair<string,string>(x.Attribute("TagName").Value,x.Attribute("TagValue").Value));

    Regex rx = new Regex(TagNamePattern);
    MatchCollection matches;
    matches = rx.Matches(input);
    foreach (Match m in matches)
    {
        KeyValuePair<string, string> tagValues = xmltags.FirstOrDefault(x => string.Format("<${0}>", x.Key) == m.Value);
        if (tagValues.Key != null && tagValues.Value != null)
        {
            input = Regex.Replace(input, string.Format(ReplacementPattern, tagValues.Key), tagValues.Value);
        }
    }
    return input;
}

我正在传递

<$Content>

和类似的东西

<Root>
  <Tag TagName="Content" TagValue="<some (escaped) HTML with>$0.26</some (escaped) HTML>"/>
</Root>

正则表达式将<$Content>替换为TagValue中的内容,但随后它返回并用<$Content>替换$ 0,因此所有小于1美元的价格都是&lt; $内容和GT; 0.26

首先,我试图理解为什么它正在这样做。我对Regexes有点熟悉,但我不知道任何会导致它的东西。第二件事是我可以做些什么来解决它。我已经考虑过在$和0之间插入一个<span/>,这样它们就不会在一起了,但这很糟糕。

0 个答案:

没有答案