我需要替换用户字符串中的变量。例如:
用户输入:Ssad asdsdqwdq jdiqwj diqw jd qwld j {price-40%} asd asd asd
我知道如何仅替换{price},但不知道如何替换其他情况。
我需要支持这些情况:
{price}
{price-xx%}
{price+xx%}
{price-xx}
{price+xx}
{price/xx}
{price*xx}
并且用户可以多次使用变量{price}。
[用户提交文本后,我的应用替换变量{price}或calc {price-xx%}并创建一个新字符串。
如果我正确理解了您的问题,那么我认为您可以在不替换变量的情况下评估整个表达式(可能必须更改变量的位置)
首先,在您的项目中添加'System.Data'命名空间
然后:
double price = 110;
double xx = 15;
double result = 0;
result = Convert.ToDouble(new DataTable().Compute($"({price-(price*xx)/100})", null));
Console.WriteLine("{price - xx%} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price + (price * xx) / 100})", null));
Console.WriteLine("{price + xx%} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price}-{xx})", null));
Console.WriteLine("{price - xx} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price}+{xx})", null));
Console.WriteLine("{price + xx} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price}/{xx})", null));
Console.WriteLine("{price / xx} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price}*{xx})", null));
Console.WriteLine("{price * xx} = " + result);