Created
March 16, 2020 11:48
-
-
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
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
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(); | |
}); | |
} | |
} |
Author
Thaina
commented
Mar 16, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment