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?

RE: Evaluating numeric expressions by FrankUray

FrankUray
Fri May 09 12:03:02 CDT 2008

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, "");



"PatrickS" wrote:

> 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?

RE: Evaluating numeric expressions by Leo

Leo
Fri May 09 13:28:01 CDT 2008

isn't that going to return 1021? what kind of evaluation is that?

"Frank Uray" wrote:

> 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, "");
>
>
>
> "PatrickS" wrote:
>
> > 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?

Re: Evaluating numeric expressions by Ben

Ben
Fri May 09 15:11:57 CDT 2008

PatrickS wrote:
> 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?

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.



Re: Evaluating numeric expressions by arne

arne
Fri May 09 20:01:48 CDT 2008

PatrickS wrote:
> 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?

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