Re: Parse string expression and get result
- From: Arne Vajhøj <arne@xxxxxxxxxx>
- Date: Fri, 27 Nov 2009 12:55:44 -0500
Arne Vajhøj wrote:
wannabe geek wrote:I need a way to successfully parse a string expression and return a number. Some examples:
"1+1" = 2
"3+4*2" = 11
"(11*(8-3))/5" = 11
"X*2" = X*2
"If((1=1)=True,1,2)" = 1
"Sum(X,3,5)+Max(1,2,3)" = X+11
I am thinking about creating a function plotter and the user must be able to create complex functions. I need to be able to use 'X' as a parameter. I also need the ablility to use any number of custom functions. I will probably be using only boolean and numeric (double perhaps?) values. I can foresee no need for comments. Could somebody guide me to a webpage that is straightforward and easy to follow? I would appreciate something quite efficient since this will be iterating quite a few times.
You can make some rather sophisticated parsers or you
can be plain lazy and decide on C# syntax and dynamicly
generate some C# code and call that.
Example:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Reflection;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
namespace E
{
public interface IFuncEval
{
double Eval(double x);
}
public class FuncEvalFactory
{
private static int n = 0;
private static Dictionary<string,IFuncEval> m = new Dictionary<string,IFuncEval>();
public static IFuncEval Create(string expr)
{
IFuncEval o = null;
if(m.ContainsKey(expr))
{
o = m[expr];
}
else
{
n++;
string cn = "FuncEval_" + n;
string src = "using System;" +
"using E;" +
"" +
"public class " + cn + " : IFuncEval" +
"{" +
" public double Eval(double x)" +
" {" +
" return " + expr + ";" +
" }" +
"}";
CodeDomProvider comp = new CSharpCodeProvider();
CompilerParameters param = new CompilerParameters();
param.GenerateInMemory = true;
param.ReferencedAssemblies.Add("System.dll");
param.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
CompilerResults res = comp.CompileAssemblyFromSource(param, src);
Assembly asm = res.CompiledAssembly;
o = (IFuncEval)asm.CreateInstance(cn);
m.Add(expr, o);
}
return o;
}
}
public class MainClass
{
public static void Test(string expr)
{
Console.WriteLine(expr + ":");
IFuncEval f = FuncEvalFactory.Create(expr);
for(int i = -2; i <= 2; i++)
{
Console.WriteLine(" " + i + " -> " + f.Eval(i));
}
}
public static void Main(string[] args)
{
Test("2*x*x-3*x+4");
Test("Math.Exp(Math.Sqrt(x+2))");
Console.ReadKey();
}
}
}
Arne
.
- References:
- Parse string expression and get result
- From: wannabe geek
- Re: Parse string expression and get result
- From: Arne Vajhøj
- Parse string expression and get result
- Prev by Date: Re: Parse string expression and get result
- Next by Date: Bitmaps
- Previous by thread: Re: Parse string expression and get result
- Next by thread: Re: Parse string expression and get result
- Index(es):
Relevant Pages
|