Last active
October 21, 2016 10:22
-
-
Save euyuil/c70b8de94220e0c4d7de to your computer and use it in GitHub Desktop.
C#: String named format parameters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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