I'm attempting to learn to write a basic template engine implementation. For example I have a string:
string originalString = "The current Date is: {{Date}}, the time is: {{Time}}";
what is the best way of reading the contents of each {{}}
and then replacing the whole token with the valid string?
EDIT: Thanks to BrunoLM for pointing me in the right direction, so far this is what I have and it parses just fine, is there any other things I can do to optimize this function?
private const string RegexIncludeBrackets = @"{{(.*?)}}";
public static string ParseString(string input)
{
return Regex.Replace(input, RegexIncludeBrackets, match =>
{
string cleanedString = match.Value.Substring(2, match.Value.Length - 4).Replace(" ", String.Empty);
switch (cleanedString)
{
case "Date":
return DateTime.Now.ToString("yyyy/MM/d");
case "Time":
return DateTime.Now.ToString("HH:mm");
case "DateTime":
return DateTime.Now.ToString(CultureInfo.InvariantCulture);
default:
return match.Value;
}
});
}