Last active
January 20, 2020 06:06
-
-
Save hikipuro/258347920d22950802555b6a0146b878 to your computer and use it in GitHub Desktop.
C#: Partially supported string interpolation (for backward compatibility)
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.Collections.Generic; | |
using System.Text.RegularExpressions; | |
public static class StringFormatter { | |
/// <summary> | |
/// How to use: | |
/// <code> | |
/// var args = new Dictionary<string, string> { | |
/// { "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