int i = 0, j = 0; int b = 0, e = 0; while (i > -1) { i = strTemp.IndexOf("(", i + 1); if (i > -1) b++; } while (j > -1) { j = strTemp.IndexOf(")", j + 1); if (j > -1) e++; } if (b != e || (b == 0 && e == 0)) return false; strTemp = strTemp.Replace("(", " "); strTemp = strTemp.Replace(")", " "); Regex reg = new Regex(@"\{\d+?\}([+\-*/]\{\d+?\})*?"); return reg.IsMatch(strTemp);试下以上。
string str = Console.ReadLine();
string pat = @"^((0|[1-9]\d*)[-+*/](0|[1-9]?\d*))+$";
Regex regex = new Regex(pat);
while (str.ToUpper().CompareTo("G")!=0)
{
Console.WriteLine(regex.IsMatch(str).ToString());
str = Console.ReadLine();
}
^[\+\-]?\d+(\.\d+)?([\+\-\*\/]\d+(\.\d+)?)*$
^ (?#匹配开头)
[-+]? (?#开头可以出现正负号)
([0-9]+(\.[0-9]+)?[-+*/])* (?#可选数-符号-数-符号-……-数-符号或结尾)
(
(
(?<o>\() (?#左括号,保存到o名字下)
[-+]? (?#可选正负号)
([0-9]+(\.[0-9]+)?[-+*/])* (?#可选数-符-数-符……)
)+ (?#可以重复出现左括号)
[0-9]+(\.[0-9]+)? (?#左右括号之间最起码需要一个操作数)
( (?#)
(?<-o>\)) (?#右括号,匹配的同时去掉一个左括号)
([-+*/][0-9]+(\.[0-9]+)?)* (?#可选符-数-符-数……)
)+ (?#可以重复出现右括号,仅当还有左括号剩余)
($|[-+*/]) (?#要么结尾,要么在下一个左括号出现之前出现一个运算符)
)* (?#重复出现左括号)
(?(o)(?!)) (?#如果还有左括号剩余就不匹配任何东西)
$ (?#匹配结尾)
", RegexOptions.IgnorePatternWhitespace);
string input = Console.ReadLine();
try
{
object o = new DataTable().Compute(input, "");
Console.WriteLine(o == null ? "不是算式" : o.ToString());
}
catch
{
Console.WriteLine("不是算式");
}
^[\+\-]?\d+(\.\d+)?([\+\-\*\/]\d+(\.\d+)?)+$
这个!
可以判断加减乘除带中括号,小括号和等号的算式。
int b = 0, e = 0;
while (i > -1)
{
i = strTemp.IndexOf("(", i + 1);
if (i > -1)
b++;
}
while (j > -1)
{
j = strTemp.IndexOf(")", j + 1);
if (j > -1)
e++;
}
if (b != e || (b == 0 && e == 0))
return false;
strTemp = strTemp.Replace("(", " ");
strTemp = strTemp.Replace(")", " ");
Regex reg = new Regex(@"\{\d+?\}([+\-*/]\{\d+?\})*?");
return reg.IsMatch(strTemp);试下以上。