- 积分
- 40165
- 好友
- 记录
- 主题
- 帖子
- 听众
- 收听
|
沙发
楼主 |
发表于 2013-2-26 11:09:22
|
只看该作者
[code=csharp]public static bool CheckExpressionValid(string input)
{
string pattern = @"^(((?<o>\()[-+]?([0-9]+[-+*/])*)+[0-9]+((?<-o>\))([-+*/][0-9]+)*)+($|[-+*/]))*(?(o)(?!))$";
//去掉空格,且添加括号便于进行匹配
return Regex.IsMatch("(" + input.Replace(" ", "") + ")", pattern);
}[/code]
[code=csharp]string[] inputs = new string[]
{
"(",
"(() ",
"1 / ",
")1 ",
"+3 ",
"((1) ",
"(1)) ",
"(1) ",
"1 + 23",
"1+2*3 ",
"1*(2+3) ",
"((1+2)*3+4)/5 ",
"1+(2*) ",
"1*(2+3/(-4)) ",
};
foreach (string input in inputs)
{
Console.WriteLine("{0}:{1} ", input, CheckExpressionValid(input));
}
Console.ReadKey();[/code]
|
|