Skip to content

Instantly share code, notes, and snippets.

@terenced
Created March 27, 2013 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save terenced/5254875 to your computer and use it in GitHub Desktop.
Save terenced/5254875 to your computer and use it in GitHub Desktop.
Extension to make string formatting for pretty ;;)
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Helpers
{
public static class StringFormatExtension
{
// http://james.newtonking.com/archive/2008/03/27/formatwith-string-format-extension-method.aspx
public static string FormatWith(this string format, params object[] args)
{
if (format == null)
throw new ArgumentNullException("format");
return string.Format(format, args);
}
public static string FormatWith(this string format, IFormatProvider provider, params object[] args)
{
if (format == null)
throw new ArgumentNullException("format");
return string.Format(provider, format, args);
}
// http://james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-named-variables.aspx
public static string FormatWith(this string format, object source)
{
return FormatWith(format, null, source);
}
public static string FormatWith(this 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>();
string rewrittenFormat = r.Replace(format, delegate(Match m)
{
Group startGroup = m.Groups["start"];
Group propertyGroup = m.Groups["property"];
Group formatGroup = m.Groups["format"];
Group 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