Как заменить переменную в пользовательском вводе математической операцией? - PullRequest
0 голосов
/ 17 февраля 2020

Мне нужно заменить переменную в строке от пользователя. Например:

Ввод пользователя: Ssad asdsdqwdq jdiqwj diqw jd qwld j {цена-40%} asd asd asd

Я знаю, как заменить только {цена}, но я не знаю, как заменить другие случаи.

Мне нужна поддержка этих случаев:

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

И пользователь может использовать переменную {price} много раз.

После того, как пользователь отправит текст, мое приложение заменит переменную {price} или cal c {price-xx%} и создаст новую строку.

Ответы [ 2 ]

0 голосов
/ 17 февраля 2020

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);
}
0 голосов
/ 17 февраля 2020

Если я правильно понял вашу проблему, то я думаю, что вы можете оценить все выражение без замены переменных (возможно, вам придется изменить размещение переменных)

Сначала добавьте пространство имен 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...