4

Есть следующий код (из инфиксной нотации в постфиксную):

string infixTerm = "2*3";
Regex reg = new Regex(@"(\d+)(\*)(\d+)");
string postfixTerm = reg.Replace(infixTerm, @"$1 $3 $2");
Console.WriteLine(postfixTerm); // ==> 2 3 *

Все хорошо, но хотелось бы заменить $1 на имя factor1, а $2 на factor2. Как можно это дело реализовать?

1 ответ 1

5

Всё просто:

Regex reg = new Regex(@"(?<factor1>\d+)(?<operator>\*)(?<factor2>\d+)");
string postfixTerm = reg.Replace(infixTerm, @"${factor1} ${factor2} ${operator}");

См. Substitutions in Regular Expressions (Подстановки в регулярных выражениях).

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.