Skip to content

Instantly share code, notes, and snippets.

@iknowcodesoup
Last active October 11, 2019 13:05
Show Gist options
  • Save iknowcodesoup/e9f5aab7536f3e1e868e43489ce5b3b2 to your computer and use it in GitHub Desktop.
Save iknowcodesoup/e9f5aab7536f3e1e868e43489ce5b3b2 to your computer and use it in GitHub Desktop.
Some common extensions used over the years in some revision or another
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
namespace Extensions
{
public static class StringExtensions
{
private static readonly Regex _keyRegex = new Regex("{([^{}:]+)(?::([^{}]+))?}", RegexOptions.Compiled);
/// <summary>
/// Named value replacement for strings (modified for ignoring case matching).
/// Pulled from FluentValidation.
/// https://github.com/JeremySkinner/FluentValidation/blob/master/src/FluentValidation/Internal/MessageFormatter.cs
/// </summary>
/// <param name="template">The template string to format</param>
/// <param name="values">The key-value based parameters to use for replacment</param>
/// <param name="ignoreCase">Whether to ignore case matching for the values</param>
/// <returns></returns>
public static string Replace(this string template, IDictionary<string, object> values, bool ignoreCase = true)
{
var formatValues = ignoreCase ? new Dictionary<string, object>(values, StringComparer.InvariantCultureIgnoreCase) : values;
return _keyRegex.Replace(template, m =>
{
var key = m.Groups[1].Value;
if (!formatValues.ContainsKey(key))
return m.Value;
var format = m.Groups[2].Success
? $"{{0:{m.Groups[2].Value}}}"
: null;
return format == null
? formatValues[key]?.ToString()
: string.Format(CultureInfo.InvariantCulture, format, formatValues[key]);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment