Created
October 24, 2013 13:42
-
-
Save kevinblake/7137555 to your computer and use it in GitHub Desktop.
FormatWith class
This file contains hidden or 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
public static class FormatWith | |
{ | |
public static string FormatString(string format, object source) | |
{ | |
return FormatString(format, null, source); | |
} | |
public static string FormatString(string format, IFormatProvider provider, object source) | |
{ | |
if (format == null) | |
{ | |
throw new ArgumentNullException("format"); | |
} | |
var r = new Regex( | |
@"(?<start>\{)+(?<property>[\w\.\[\]]+)(?<format>:[^}]+)?(?<end>\})+", | |
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); | |
var values = new List<object>(); | |
var rewrittenFormat = r.Replace( | |
format, | |
delegate(Match m) | |
{ | |
var startGroup = m.Groups["start"]; | |
var propertyGroup = m.Groups["property"]; | |
var formatGroup = m.Groups["format"]; | |
var endGroup = m.Groups["end"]; | |
values.Add((propertyGroup.Value == "0") ? source : DataBinder.Eval(source, propertyGroup.Value)); | |
return new string('{', startGroup.Captures.Count) + (values.Count - 1) + formatGroup.Value + | |
new string('}', endGroup.Captures.Count); | |
}); | |
return string.Format(provider, rewrittenFormat, values.ToArray()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment