Regex.Replace callback - get Dictionary key from matched group

Viewed 31

I'm working on the backend of very small website which has an extremely basic template system using HTML comments. It was previously on PHP and is being migrated to .NET. This was accomplished in PHP with preg_replace_callback.

I need to replace <!--[var:title]--> with the title key in a Dictionary.

I have a basic function to load a template

let loadTemplate templateName =
    if templateName |> templateExists then
        templateName
        |> getTemplateFilePath
        |> File.ReadAllText
        |> ReplaceVariables
    else
        "<!--[Missing Template: " + templateName + "]-->"

Where

let varReplaceCallback (matchedVar: Match) =
    printfn "%O" matchedVar
    "Hello"
    //Here is where I need help. I need to return a dictionary with key (.*?)

let ReplaceVariables (string:string) =
    Regex.Replace(string, "<!--\[var\:(.*?)\]-->", MatchEvaluator varReplaceCallback)

I would have expected varReplaceCallbackto have received the group (.*?) but instead it receives the full match <!--[var:whatever]-->

So is Regex.Replace the right thing to be using here?

1 Answers

Oops, super easy. Didn't know enough about the match type

let varReplaceCallback (matchedVar: Match) =
    let varName = matchedVar.Groups.[1] |> string
    values.[varName] //Where values is a map/dictionary
Related