2010-08-05 53 views
0

我正在构建一个自定义页面缓存实用程序,它使用像{Substitution:GetNonCachedData}这样的语法来获取不应该被缓存的数据。该解决方案非常类似于内置的<@ OutputCache %>,但不够灵活(我不需要它),最重要的是,允许会话状态在检索非缓存数据时可用。我需要帮助做一个正则表达式。替换多个结果

无论如何,我有一个方法,用{Substitution}标记中指定的静态方法的结果替换HTML中的标记。

例如我的网页:

<html> 
    <body> 
     <p>This is cached</p> 
     <p>This is not: {Substitution:GetCurrentTime}</p> 
    </body> 
</html> 

将在{Substitution:GetCurrentTime}填充静态方法的结果。下面是其中的处理情况:

private static Regex SubstitutionRegex = new Regex(@"{substitution:(?<method>\w+)}", RegexOptions.IgnoreCase); 

public static string WriteTemplates(string template) 
{ 
    foreach (Match match in SubstitutionRegex.Matches(template)) 
    { 
     var group = match.Groups["method"]; 
     var method = group.Value; 
     var substitution = (string) typeof (Substitution).GetMethod(method).Invoke(null, null); 
     template = SubstitutionRegex.Replace() 
    } 

    return template; 

} 

变量template是在它需要更换定制令牌的HTML。这种方法的问题是,每次我用更新的html更新template变量时,match.Index变量不再指向正确的字符起点,因为template现在增加了更多字符。

我可以想出一个解决方案,通过计算字符等或其他一些螺旋球的方式来做到这一点,但我首先要确保没有一些更简单的方法来实现这个正则表达式对象。任何人都知道如何?

谢谢!

回答

1

您应该调用Regex.Replace的超载,该代码需要MatchEvaluator委托。

例如:

return SubstitutionRegex.Replace(template, delegate(Match match) { 
    var group = match.Groups["method"]; 
    var method = group.Value; 
    return (string) typeof (Substitution).GetMethod(method).Invoke(null, null); 
}); 
+0

你能举个例子吗? – Micah 2010-08-05 18:14:50

+0

@Michah:你来了。 – SLaks 2010-08-06 05:36:33

0

而不是使用火柴和循环的结果,将正则表达式来编译和while循环使用一个单一的比赛,直到它停止匹配。