Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Evaluating numeric expressions

2 views
Skip to first unread message

PatrickS

unread,
May 9, 2008, 4:49:01 AM5/9/08
to
Is there an easy way in C# to take a string that contains an expression, say
for example something like '(10 / 2) + 1' and evaluate it without having to
parse the string myself and muck about with other stuff like operator
precedence?

Frank Uray

unread,
May 9, 2008, 1:03:02 PM5/9/08
to
Maybe you can try with RegularExpressions

string local_pattern = @"[^0-9]";
System.Text.RegularExpressions.Regex local_RegEx = new
System.Text.RegularExpressions.Regex(local_pattern);
return local_RegEx.Replace(local_InputString, "");

Seccia@discussions.microsoft.com Leo Seccia

unread,
May 9, 2008, 2:28:01 PM5/9/08
to
isn't that going to return 1021? what kind of evaluation is that?

Ben Voigt [C++ MVP]

unread,
May 9, 2008, 4:11:57 PM5/9/08
to

You can invoke the C# compiler to create a class with a static method, then
call the method. Doing this without memory leaks is not easy and very bad
performance.

I would look into JScript.NET which has an eval function.


Arne Vajhøj

unread,
May 9, 2008, 9:01:48 PM5/9/08
to

JavaScript has a nice eval function that can be utilized from C#.

See http://www.vajhoej.dk/arne/eksperten/div_2007_08/evaljs.cs for
a code example.

Arne

0 new messages