If you don't mind dynamic code, you could do something like so:
string code = "Math.Pow(23 + 48, 2) - (7.76 * 3.14)";
string result = Eval.StringEval(code);
Console.WriteLine("Results: " + result);
Output
-------------------
Results: 5016.6336
Eval Class
--------------------
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
public static class Eval
{
private static string funcprefix = "using System;\r\n"
+ "public delegate void Proc();\r\n"
+ "public class Wrapper { \r\n"
+ " public static object Set(string name, object value) { \r\n"
+ " AppDomain.CurrentDomain.SetData(name, value);\r\n"
+ " return value; \r\n"
+ " }\r\n"
+ " public static object Get(string name) { \r\n"
+ " return AppDomain.CurrentDomain.GetData(name);\r\n"
+ " }\r\n"
+ " public static object Invoke(Proc proc) { \r\n"
+ " proc();\r\n"
+ " return null; \r\n"
+ " }\r\n"
+ " public static object Eval() { return \r\n";
static string funcsuffix = "; \r\n} }";
public static string StringEval(string expr)
{
string program = funcprefix + expr + funcsuffix;
CompilerParameters cp = new CompilerParameters();
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
CompilerResults results =
CodeDomProvider.CreateProvider("C#").CompileAssemb lyFromSource(cp, new
string[]{program});
if ( results.Errors.HasErrors )
{
if ( results.Errors[0].ErrorNumber == "CS0029" )
return StringEval("Invoke(delegate { " + expr + "; })");
throw new Exception(results.Errors[0].ErrorText);
}
else
{
Assembly assm = results.CompiledAssembly;
Type target = assm.GetType("Wrapper");
MethodInfo method = target.GetMethod("Eval");
object result = method.Invoke(null, null);
return result == null ? null : result.ToString();
}
}
}
--
William Stacey [MVP]
"Janiek Buysrogge" <J.*********@Televic.com> wrote in message
news:2j********************************@4ax.com...
Hello,
Does anyone know if there is a library or a sample project that can
parse strings with mathematical expressions inside ?
eg. string math = "(23 + 48) ^ 2 - (7.76 * 3.14)";
parser should calculate the result of this.
Atm I have my own parser, but it can only handle very simple
expressions with 2 operands eg. (34 * 89), I tried to expand the
functionality, but it's getting ugly (loads of substrings).
Any pointers ?
Thanks,
Janiek