用C#计算一个特殊表达式

本文关键字:一个 表达式 计算 | 更新日期: 2023-09-27 18:29:16

我有一个字符串,它有一个特殊格式的特殊子字符串:

$(variableName

这种模式可以重复嵌套多次:

$(variableName$(anotherVariableName))

例如:[A测试字符串]

这是一个测试字符串,包含$(variableA)和$(可变B$(可变C))

对于这个测试字符串,假设

$(variableA)=A,$(variable B)=B,$(variableC)=C,$(可变BC)=Y

我想要的是用实际值替换那些特殊的模式->$(variableName),比如结果字符串应该是:

这是一个包含a和Y 的测试字符串

有什么关于通用优雅解决方案的建议吗?

用C#计算一个特殊表达式

这里有一个执行递归下降解析的简单解决方案

public static string Replace(
    string input
,   ref int pos
,   IDictionary<string,string> vars
,   bool stopOnClose = false
) {
    var res = new StringBuilder();
    while (pos != input.Length) {
        switch (input[pos]) {
            case '''':
                pos++;
                if (pos != input.Length) {
                    res.Append(input[pos++]);
                }
                break;
            case ')':
                if (stopOnClose) {
                    return res.ToString();
                }
                res.Append(')');
                pos++;
                break;
            case '$':
                pos++;
                if (pos != input.Length && input[pos] == '(') {
                    pos++;
                    var name = Replace(input, ref pos, vars, true);
                    string replacement;
                    if (vars.TryGetValue(name, out replacement)) {
                        res.Append(replacement);
                    } else {
                        res.Append("<UNKNOWN:");
                        res.Append(name);
                        res.Append(">");
                    }
                    pos++;
                } else {
                    res.Append('$');
                }
                break;
            default:
                res.Append(input[pos++]);
                break;
        }
    }
    return res.ToString();
}
public static void Main() {
    const string input = "Here is a test string contain $(variableA) and $(variableB$(variableC))";
    var vars = new Dictionary<string, string> {
        {"variableA", "A"}, {"variableB", "B"}, {"variableC", "C"}, {"variableBC", "Y"}
    };
    int pos = 0;
    Console.WriteLine(Replace(input, ref pos, vars));
}

此解决方案重用Replace的实现,通过使用设置为truestopOnClose标志调用自身来构建要替换的变量的名称。顶级调用不会在到达')'符号时停止,从而允许您在未跳过的情况下使用它。

这是ideone上的演示。