Template replacement engine

By | 2017.04.19

Using Regex as a template engine is an efficient way to replace strings in a template. Regex replace method supports executing a method upon match. We can populate a dictionary and make a lookup on all matches. This way we do the replacement in a single pass, rather than executing multiple .Replace(). Since dictionaries can be made case insensitive we have an efficient way of doing case insensitive replacement, something .Replace() does not support.


I have kept support for escaping [ and ] using \[ and \]. This does add a second pass to the template. Also you may want to add RegexOptions.Compiled (as last parameter on Replace-call, see next example).

Cleaning up the code a bit we see how this can look nice:

Taking it to the next level we could even populate the replacement data from a model:

The output would be:

Leave a Reply