C#字符串实现宏替换

宏:

MacroTotal 123
MacroY2Y 456
MacroM2M 789

模板:

“本季度总额{MacroTotal},同比增长{MacroY2Y}%,环比增长{MacroM2M}%”

宏替换实现:

    
private readonly string LeftSign = "{";
private readonly string RightSign = "}";

public void PreviewConclusion(string content)
{
    var list = GetInnerString(LeftSign, RightSign, ref content);
    
    //MacroList就是已计算出相关值的宏列表,这里生成Dictionary便于取值
    var dict = MacroList.ToDictionary(k => { return k.Macro; }, v => { return v.Value + string.Empty; });

    var values = new object[list.Count];
    for (var i = 0; i < values.Length; i++)
    {
	    if (dict.ContainsKey(list[i]))
	    {
		    values[i] = dict[list[i]];
	    }
	    else
	    {
            //没有这个宏,则保留原样
		    values[i] = $"{LeftSign}{list[i]}{RightSign}";
	    }
    }

    string conclusion = string.Format(content, values);
}

public List GetInnerString(string prefix, string postfix, ref string source)
{
	Match match = new Regex("(?<=(" + prefix + "))[0-9A-Za-z_]*?(?=(" + postfix + "))", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline).Match(source);
	int num = 0;
	List list = new List();
	while (match.Success)
	{
		list.Add(Regex.Replace(match.Value, "\\s*|\t|\r|\n", ""));
		source = source.Replace("{" + match.Value + "}", $"{{{num++}}}");
		match = match.NextMatch();
	}

	return list;
}

你可能感兴趣的:(c#)