Forked from terenced/string-format-extension.cs
Last active
December 17, 2015 10:19
-
-
Save ramonsmits/5593913 to your computer and use it in GitHub Desktop.
Added alignment support for named values.
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
using System; | |
using System.Collections.Generic; | |
using System.Text.RegularExpressions; | |
using System.Web; | |
using System.Web.UI; | |
namespace StringExtensions | |
{ | |
/// <remarks> | |
/// http://james.newtonking.com/archive/2008/03/27/formatwith-string-format-extension-method.aspx | |
/// http://james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-named-variables.aspx | |
/// http://haacked.com/archive/2009/01/14/named-formats-redux.aspx | |
/// </remarks> | |
public static class JamesFormatter | |
{ | |
static readonly Regex NamedFormatRegex = new Regex(@"(?<start>\{)+(?<property>[\w\.\[\]]+)(?<align>,\-?\d+)?(?<format>:[^}]+)?(?<end>\})+", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); | |
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 values = new List<object>(); | |
string rewrittenFormat = NamedFormatRegex.Replace(format, delegate(Match m) | |
{ | |
Group startGroup = m.Groups["start"]; | |
Group propertyGroup = m.Groups["property"]; | |
Group alignGroup = m.Groups["align"]; | |
Group formatGroup = m.Groups["format"]; | |
Group endGroup = m.Groups["end"]; | |
values.Add((propertyGroup.Value == "0") ? source : Eval(source, propertyGroup.Value)); | |
int openings = startGroup.Captures.Count; | |
int closings = endGroup.Captures.Count; | |
return openings > closings || openings % 2 == 0 ? m.Value : new string('{', openings) + (values.Count - 1) + alignGroup.Value + formatGroup.Value + new string('}', closings); | |
}); | |
return string.Format(provider, rewrittenFormat, values.ToArray()); | |
} | |
private static object Eval(object source, string expression) | |
{ | |
try | |
{ | |
return DataBinder.Eval(source, expression); | |
} | |
catch (HttpException e) | |
{ | |
throw new FormatException(null, e); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment