Expression parser

  • Thread starter Thread starter Joe
  • Start date Start date
J

Joe

I have a screen which allows the user to create mathematical expressions
using a combination of literal values, other expressions and field values.


For example if I have the following:

// fields
string val1 = "2";
string val2 = "1";
string val3 = "4.5";

//expressions
string expr1 = "8 * val1 / val2 + val3";
string expr2 = "val2 * expr1 + 3";

I need to parse this out to perform the actually calculation.
string expr2 would expand to 1 * 8 * 2 / 1 + 3 + 3;

Any suggestions on how to do this? I already created a number of classes to
handle this but I'm still missing some possible combinations.
 
there are a couple of open source expression evaluators that may be a good
place to look. You need to remember operator precedence and a few other
things if you are going to do this right... or you could just use one of
these classes...

Here are some links
http://www.codeproject.com/csharp/Expression_Evaluator.asp
http://www.codeproject.com/csharp/runtime_eval.asp
http://www.codeproject.com/vb/net/math_expression_evaluator.asp
http://www.programmersheaven.com/zone3/cat478/23301.htm
http://sourceforge.net/projects/cexev/


--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
 
You can do this with Regular expressions. Francesco Balena's book
"Programming Microsoft Visual Basic.Net" has a complete solution with full
code on the companion CD. There is a newer version of the book for .Net
2003 but it still has all the code you need. It is surprisingly compact
when done with Regex and uses only one class to do all the work.

Robby
 
Thanks. This is just what I needed it.

Nick Malik said:
there are a couple of open source expression evaluators that may be a good
place to look. You need to remember operator precedence and a few other
things if you are going to do this right... or you could just use one of
these classes...

Here are some links
http://www.codeproject.com/csharp/Expression_Evaluator.asp
http://www.codeproject.com/csharp/runtime_eval.asp
http://www.codeproject.com/vb/net/math_expression_evaluator.asp
http://www.programmersheaven.com/zone3/cat478/23301.htm
http://sourceforge.net/projects/cexev/


--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
 
Back
Top