Template replacement engine

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.

Example:

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Tedds blog

Subscribe now to keep reading and get access to the full archive.

Continue reading