寫了一個判斷四則運算合法性較驗的式子。
public static bool CheckExpressionValid(string input) { string pattern = @"^(((?<o>\()[-+]?([0-9]+[-+*/])*)+[0-9]+((?<-o>\))([-+*/][0-9]+)*)+($|[-+*/]))*(?(o)(?!))$"; //去掉空格,且添加括號便於進行匹配 return Regex.IsMatch("(" + input.Replace(" ", "") + ")", pattern); }
public static bool CheckExpressionValid(string input) { string pattern = @"^(((?<o>\()[-+]?([0-9]+[-+*/])*)+[0-9]+((?<-o>\))([-+*/][0-9]+)*)+($|[-+*/]))*(?(o)(?!))$"; //去掉空格,且添加括號便於進行匹配 return Regex.IsMatch("("+ input.Replace(" ", "") + ")", pattern); }
較難的地方在於括號的匹配,(? <o> \()是用來把左括號保存到o變量下,對應於(? <-o> \))用來去掉左括號,(?(o)(?!)) 是匹配完了右括號后,如果還剩下左括號,則不需再進行匹配。
測試代碼
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();
項目中用到的地方是與此略有不同,表達式為:"產品面積*單價",所以調用CheckExpressionValid函數前需要再轉換一下,轉換較為簡單,將"產品面積"替換成數字即可,[\u4e00-\u9fa5])+用來匹配中文。
private static bool CheckCalcExpressionValid(string expression) { string parttern = @"(產品面積|單價|印張數量)\.([\u4e00-\u9fa5])+"; string matchparttern = "1 "; return CheckExpressionValid(Regex.Replace(expression, parttern, matchparttern)); }