简体   繁体   中英

How to Validate mathematical formula expressions using regex

I am looking for mathematical formula validation using regex. Here is the example code that I am using:-

 string equation = "(a+b)*10";

 bool b = false;

 Regex rx = new Regex(@"^((?<o1>[^-+*/()]+|\([^-+*/()]+\)|(?<p>\()+[^-+*/()]+|[^-+*/()]+(?<-p>\)))[-+*/])+(?<o2>[^-+*/()]+|\([^-+*/()]+\)|(?<p>\()+[^-+*/()]+|[^-+*/()]+(?<-p>\)))(?(p)(?!))$");

 if (rx.IsMatch(equation))
     {
      b = true;
     }

It is working fine with the expression used Like "(a+b)*100". I mean If I go for wrong placement of braces like "(a+b))*100" or "(a+b*100" or "(a+b)*100)" it is doing perfect validation. But if go for introduction of my user defined functions like "Sum(1,2)" or Sqrt(8) It is failing to validate.

I want this to validate my functions also. Like "Sum(1,2)","Sum(1,2" ,"Sum1,2)", "Sum(1,2))". I mean it should take care of proper usage of braces.

Note:- I am using ANTLR to create these funations.

Thanks

A generic mathematical formula would be too complex to parse using a regular expression. Use ANTLR to write a grammar that can parse out the individual elements instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM