C# 如何替换字符串模板上的标记?

C# 如何替换字符串模板上的标记?,c#,template-engine,c#-6.0,C#,Template Engine,C# 6.0,我试图学习编写一个基本的模板引擎实现。例如,我有一个字符串: string originalString = "The current Date is: {{Date}}, the time is: {{Time}}"; 读取每个{{}的内容,然后用有效字符串替换整个标记的最佳方法是什么 编辑:感谢BrunoLM为我指出了正确的方向,到目前为止,这就是我所拥有的,它解析得很好,我还可以做些什么来优化这个函数 private const string RegexIncludeBrackets =

我试图学习编写一个基本的模板引擎实现。例如,我有一个字符串:

string originalString = "The current Date is: {{Date}}, the time is: {{Time}}";
读取每个
{{}
的内容,然后用有效字符串替换整个标记的最佳方法是什么

编辑:感谢BrunoLM为我指出了正确的方向,到目前为止,这就是我所拥有的,它解析得很好,我还可以做些什么来优化这个函数

private const string RegexIncludeBrackets = @"{{(.*?)}}";

public static string ParseString(string input)
{
    return Regex.Replace(input, RegexIncludeBrackets, match =>
    {
        string cleanedString = match.Value.Substring(2, match.Value.Length - 4).Replace(" ", String.Empty);
        switch (cleanedString)
        {
            case "Date":
                return DateTime.Now.ToString("yyyy/MM/d");
            case "Time":
                return DateTime.Now.ToString("HH:mm");
            case "DateTime":
                return DateTime.Now.ToString(CultureInfo.InvariantCulture);
            default:
                return match.Value;
        }
    });
}
简短回答 我认为最好使用正则表达式

var result = Regex.Replace(str, @"{{(?<Name>[^}]+)}}", m =>
{
    return m.Groups["Name"].Value; // Date, Time
});

String.Format&可附加 然而,已经有了一种方法

此外,您还可以使用带有
IFormattable
的类。我没有做性能测试,但这一次可能很快:

public class YourClass : IFormattable
{
    public string ToString(string format, IFormatProvider formatProvider)
    {
        if (format == "Date")
            return DateTime.Now.ToString("yyyy/MM/d");
        if (format == "Time")
            return DateTime.Now.ToString("HH:mm");
        if (format == "DateTime")
            return DateTime.Now.ToString(CultureInfo.InvariantCulture);

        return format;

        // or throw new NotSupportedException();
    }
}
并用作

String.Format("The current Date is: {0:Date}, the time is: {0:Time}", yourClass);

查看您的代码和详细信息 在您当前使用的代码中

// match.Value = {{Date}}
match.Value.Substring(2, match.Value.Length - 4).Replace(" ", String.Empty);
相反,如果你看一下我上面的代码,我使用了这个模式

@"{{(?<Name>[^}]+)}}"
要进一步改进,可以使用静态编译的正则表达式字段:

private static Regex RegexTemplate = new Regex(@"{{(?<Param>.*?)}}", RegexOptions.Compiled);

努力吧!!!。一个简单的谷歌搜索可以得到提示,阅读MSDN中的
boxing/unboxing
String.Format
,这可能是@BrunoLM的副本,如果OP显示出哪怕是最轻微的努力解决问题的迹象,我都很乐意提供帮助。我想知道为什么这是来自一个20k+的代表user@BrunoLM谢谢你给我指明了正确的方向。我接受了你对regex的最初想法,并补充道:没问题,很高兴我能帮上忙。
@"{{(?<Name>[^}]+)}}"
private const string RegexIncludeBrackets = @"{{(?<Param>.*?)}}";

public static string ParseString(string input)
{
    return Regex.Replace(input, RegexIncludeBrackets, match =>
    {
        string cleanedString = match.Groups["Param"].Value.Replace(" ", String.Empty);
        switch (cleanedString)
        {
            case "Date":
                return DateTime.Now.ToString("yyyy/MM/d");
            case "Time":
                return DateTime.Now.ToString("HH:mm");
            case "DateTime":
                return DateTime.Now.ToString(CultureInfo.InvariantCulture);
            default:
                return match.Value;
        }
    });
}
private static Regex RegexTemplate = new Regex(@"{{(?<Param>.*?)}}", RegexOptions.Compiled);
RegexTemplate.Replace(str, match => ...);