如何用数学运算替换用户输入中的变量?



>我需要替换用户字符串中的变量。例如:

User input:Ssad asdsdqwdq jdiqwj diqw jd qwld j {price-40%} asd asd asd

我知道如何只替换{价格},但我不知道如何替换其他情况。

我需要支持这些情况:

{price}
{price-xx%}
{price+xx%}
{price-xx}
{price+xx}
{price/xx}
{price*xx}

用户可以多次使用变量{价格}。

用户提交文本后,我的应用会替换变量 {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);

> https://github.com/davideicardi/DynamicExpresso/

static void Main(string[] args)
{
int price = 100;
Regex regex = new Regex(@"(?<={).*?(?=})");
string userInput = "Hi. I want to buy your computer. I can't offer {price} USD, but I can offer {price-(price/100)*10} USD";
string text = userInput;
foreach (var item in regex.Matches(text))
{
string expression = item.ToString().Replace("price", price.ToString());
var interpreter = new Interpreter();
var result = interpreter.Eval(expression);
text = regex.Replace(text, result.ToString(),1);
text = ReplaceFirst(text, "{", string.Empty);
text = ReplaceFirst(text, "}", string.Empty);
}
Console.WriteLine("Result: " + text);
}
public static string ReplaceFirst(string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}

最新更新