Evaluating numeric expressions

  • Thread starter Thread starter PatrickS
  • Start date Start date
P

PatrickS

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?
 
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, "");
 
isn't that going to return 1021? what kind of evaluation is that?

Frank Uray said:
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 said:
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?
 
PatrickS said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top