首页 > 解决方案 > 解析表达式的最佳方法 - 多个变量

问题描述

我有一种情况,我需要解析多个 n 个相关字段(不想评估):

    string exp1 = "10";
    string exp2 = "20";
    string exp3= "exp1 + exp2 + 30";
    string exp4 = "exp5 - exp3"; 
    string exp5 = "exp3 / 10";

    Dictionary<string,string> expressions = new Dictionary<string,string>();
    expressions.Add("exp1", exp1);
    expressions.Add("exp2", exp2);
    expressions.Add("exp3", exp3);
    expressions.Add("exp4", exp3);
    expressions.Add("exp5", exp5);

现在我们要遍历所有表达式字段并用实际值解析表达式(也应该应用 Bodmas)。所以,解析后,我们希望下面作为输出:

exp1 = "10";
exp2 = "20";
exp3= "10 + 20 + 30";
exp4 = "((10 + 20 + 30 )/10) - (10+ 20 + 30)";
exp5 = "(10 + 29 + 30)/ 10";

我应该在这里使用什么数据结构来使用通用方式解析它?会是二叉树、图表、表达式树吗?

标签: c#

解决方案


编码

using System.Collections.Generic;
using Microsoft.VisualBasic;    //the code was written in VB and converted. make appropriate changes if you don't want to use this namespace

class Exp
{
    private Dictionary<string, string> AllExpressions = new Dictionary<string, string>();

    public void Add(string name, string value)
    {
        AllExpressions.Add(name, value);
    }

    public string ValueOf(string name)
    {
        var parts = Strings.Split(AllExpressions[name]);
        for (int i = 0; i <= parts.Length - 1; i++)
        {
            if (AllExpressions.ContainsKey(parts[i]))
            {
                var partVal = ValueOf(parts[i]);
                parts[i] =  Information.IsNumeric(partVal) ? partVal : $"({partVal})";
            }
        }
        return Strings.Join(parts);
    }
}

用法

Exp myExp = new Exp();
myExp.Add("exp1", "10");
myExp.Add("exp2", "20");
myExp.Add("exp3", "exp1 + exp2 + 30");
myExp.Add("exp4", "exp5 - exp3");
myExp.Add("exp5", "exp3 / 10");

// Test to see if we can get correct values 
Console.WriteLine(myExp.ValueOf("exp1"));
Console.WriteLine(myExp.ValueOf("exp2"));
Console.WriteLine(myExp.ValueOf("exp3"));
Console.WriteLine(myExp.ValueOf("exp4"));
Console.WriteLine(myExp.ValueOf("exp5"));

结果

10
20
10 + 20 + 30
((10 + 20 + 30) / 10) - (10 + 20 + 30)
(10 + 20 + 30) / 10

推荐阅读