簡體   English   中英

我需要做Regex.Replace有多個結果的幫助

[英]I need help doing a Regex.Replace with multiple results

我正在構建一個自定義頁面緩存實用程序,該實用程序使用諸如{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現在添加了更多字符。

我可以想出一種可以通過計算字符數或其他方式實現的解決方案,但是我首先要確保沒有使用Regex對象實現此目的的簡便方法。 有人知道該怎么做嗎?

謝謝!

您應該調用帶有MatchEvaluator委托的Regex.Replace重載。

例如:

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

將正則表達式設置為已編譯,然后在while循環中使用單個Match,直到它停止匹配,而不是使用Matches並在結果上循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM