private static string EvaluateMatch(Match match)
{
if (match.Groups[1].Value == "" || match.Groups[3].Value == "")
{
return "";
}
int num1 = int.Parse(match.Groups[1].Value);
string op = match.Groups[2].Value;
int num2 = int.Parse(match.Groups[3].Value);
int result = 0;
switch (op)
{
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0)
{
throw new DivideByZeroException("Деление на ноль");
}
result = num1 / num2;
break;
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
}
return result.ToString();
}
private string ReplaceMulAndDiv(string s) // * /
{
string pattern = @"(\d+)\s*[*\/]\s*(\d+)";
MatchEvaluator m = new MatchEvaluator(EvaluateMatch);
return Regex.Replace(s, pattern, m);
}
private string ReplaceSumAndSub(string s) // + -
{
string pattern = @"(\d+)\s*[+-]\s*(\d+)";
MatchEvaluator m = new MatchEvaluator(EvaluateMatch);
return Regex.Replace(s, pattern, m);
}
private bool ValidInput(string input)
{
string pattern = @"^\d+\s*([+\-*/]\s*\d+)*$";
return Regex.IsMatch(input, pattern);
}
private void button11_Click(object sender, EventArgs e) // =
{
var s = textBox1.Text;
if (ValidInput(s))
{
while (s.Contains("*") || s.Contains("/"))
{
s = ReplaceMulAndDiv(s);
}
while (s.Contains("+") || s.Contains("-"))
{
s = ReplaceSumAndSub(s);
}
textBox1.Text = s;
}
else
{
MessageBox.Show("Некорректный ввод", "!!!Ошибка!!!", MessageBoxButtons.OKCancel);
}
}
private void button17_Click(object sender, EventArgs e) //CE
{
textBox1.Clear();
}
private void button10_Click(object sender, EventArgs e) // <-
{
if (textBox1.Text != "")
{
textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1, 1);
}
}
private void button0_Click(object sender, EventArgs e) // все кнопки цифр и мат.действий
{
textBox1.Text += (sender as Button).Text;
}