Skip to content

Instantly share code, notes, and snippets.

@euyuil
Last active October 21, 2016 10:22
Show Gist options
  • Save euyuil/c70b8de94220e0c4d7de to your computer and use it in GitHub Desktop.
Save euyuil/c70b8de94220e0c4d7de to your computer and use it in GitHub Desktop.
C#: String named format parameters.
// Modified based on http://stackoverflow.com/questions/1322037/
public static class StringUtils
{
private static Regex FormatPattern =
new Regex(@"(\{+)([^\}]+)(\}+)", RegexOptions.Compiled);
public static string Format(this string pattern, object template)
{
if (template == null)
{
throw new ArgumentNullException("template");
}
var type = template.GetType();
var cache = new Dictionary<string, string>();
return FormatPattern.Replace(pattern, match =>
{
var lCount = match.Groups[1].Value.Length;
var rCount = match.Groups[3].Value.Length;
if ((lCount % 2) != (rCount % 2))
{
throw new InvalidOperationException("Unbalanced braces");
}
var lBrace = lCount == 1 ? "" : new string('{', lCount / 2);
var rBrace = rCount == 1 ? "" : new string('}', rCount / 2);
var key = match.Groups[2].Value;
string value;
if (lCount % 2 == 0)
{
value = key;
}
else
{
if (!cache.TryGetValue(key, out value))
{
var prop = type.GetProperty(key);
if (prop == null)
{
throw new ArgumentException("Not found: " + key, " pattern");
}
value = Convert.ToString(prop.GetValue(template, null));
cache.Add(key, value);
}
}
return lBrace + value + rBrace;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment