我正在写一个求解方程的求解方法.该方法将是递归的; 搜索所有外括号并在找到时调用求解括号内的值,并在未找到括号时返回该值.
这个过程应该是这样的
20 * (6+3) / ((4+6)*9)
20 * 9 / ((4+6)*9)
20 * 9 / (10*9)
20 * 9 / 90
2
Run Code Online (Sandbox Code Playgroud)
如您所见,每场比赛可能有不同的替换值.我需要将括号替换为它的计算结果.有没有办法做到这一点.这是我到目前为止所拥有的.
public int solve(string etq)
{
Regex rgx = new Regex(@"\(([^()]|(?R))*\)");
MatchCollection matches;
matches = rgx.Matches(etq);
foreach(Match m in matches){
//replace m in etq with unique value here
}
//calculations here
return calculation
}
Run Code Online (Sandbox Code Playgroud)
Regex.replace(...)替换所有出现的指定模式.我希望能够匹配多个场景并用不同的输出替换每个场景
简单方案:
string input = "20 * (6+3) / ((4+6)*9)";
Console.WriteLine(input);
DataTable dt = new DataTable();
Regex rx = new Regex(@"\([^()]*\)");
string expression = input;
while (rx.IsMatch(expression))
{
expression = rx.Replace(expression, m => dt.Compute(m.Value, null).ToString(), 1);
Console.WriteLine(expression);
}
Console.WriteLine(dt.Compute(expression, null));
Run Code Online (Sandbox Code Playgroud)
https://dotnetfiddle.net/U6Hh1e