Skip to content

Instantly share code, notes, and snippets.

@hikipuro
Last active January 20, 2020 06:06
Show Gist options
  • Save hikipuro/258347920d22950802555b6a0146b878 to your computer and use it in GitHub Desktop.
Save hikipuro/258347920d22950802555b6a0146b878 to your computer and use it in GitHub Desktop.
C#: Partially supported string interpolation (for backward compatibility)
using System.Collections.Generic;
using System.Text.RegularExpressions;
public static class StringFormatter {
/// <summary>
/// How to use:
/// <code>
/// var args = new Dictionary&lt;string, string&gt; {
/// { "test", "def" }
/// };
/// var str = StringFormatter.Format("abc {test} ghi", args);
/// Console.WriteLine(str); // abc def ghi
/// </code>
/// </summary>
/// <param name="format"></param>
/// <param name="args"></param>
/// <returns></returns>
public static string Format(string format, Dictionary<string, string> args) {
if (string.IsNullOrEmpty(format) || args == null) {
return format;
}
Regex regex = new Regex(@"{{|}}|{([^}]+)}");
return regex.Replace(format, (Match match) => {
switch (match.Value) {
case "{{":
return "{";
case "}}":
return "}";
}
if (match.Groups.Count < 2) {
return string.Empty;
}
string value = match.Groups[1].Value;
if (args.ContainsKey(value) == false) {
return string.Empty;
}
return args[value];
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment