Skip to content

Instantly share code, notes, and snippets.

@Thaina
Created March 16, 2020 11:48
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 Thaina/b0e59bbb32c8531c09d40d2e1d5abf44 to your computer and use it in GitHub Desktop.
Save Thaina/b0e59bbb32c8531c09d40d2e1d5abf44 to your computer and use it in GitHub Desktop.
C# style string formatter using regex to search for key and replace with IFormattable.Format
using System;
using System.Linq;
using System.Text.RegularExpressions;
public static class RegexFormatter
{
static readonly Regex FormatterPattern = new Regex(@"\{([^\{\}]+?)(?:\:([^\{\}]*))?\}",RegexOptions.Multiline);
public static string RegexFormat(this string input,Func<string,object> selector)
{
return FormatterPattern.Replace(input,(match) => {
var capture = match?.Groups?.OfType<Group>().Skip(1).Select((group) => group.Value).ToArray();
if(!(capture?.FirstOrDefault() is string key && selector(key) is var value && value != null))
return match.Value;
return capture.Length > 1 && value is IFormattable formattable ? formattable.ToString(capture[1],null) : value.ToString();
});
}
}
@Thaina
Copy link
Author

Thaina commented Mar 16, 2020

Console.WriteLine("{0}".RegexFormat((key) => 100 / 3f)); // 33.33333
Console.WriteLine("{0:000.00}".RegexFormat((key) => 100 / 3f)); // 033.33

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment