Skip to content

Instantly share code, notes, and snippets.

@kevinblake
Created October 24, 2013 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinblake/7137555 to your computer and use it in GitHub Desktop.
Save kevinblake/7137555 to your computer and use it in GitHub Desktop.
FormatWith class
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