I need a fast runtime expression parser

坚强是说给别人听的谎言 提交于 2019-11-26 18:37:46
GreyCloud

Have you seen https://ncalc.codeplex.com/ and https://github.com/sheetsync/NCalc ?

It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:

Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");

  e.Parameters["Pi2"] = new Expression("Pi * Pi");
  e.Parameters["X"] = 10;

  e.EvaluateParameter += delegate(string name, ParameterArgs args)
    {
      if (name == "Pi")
      args.Result = 3.14;
    };

  Debug.Assert(117.07 == e.Evaluate());

It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.

It also supports logical operators, date/time's strings and if statements.

Corbin March

How about the Fast Lightweight Expression Evaluator? It lets you set variables and supports logical operators.

If you need something beefier and have the time, you could also design your own expression language with Irony.

Hisystems' Interpreter supports custom functions, operators and literals, is lightweight pure c# portable code. Currently runs on iOS via MonoTouch and should run on any other Mono environment as well as windows. Free for commercial use. Available on GitHub at https://github.com/hisystems/Interpreter.

I fully appreciate how late this answer is however I would like to throw in my solution because I believe it can add more above the accepted answer of using NCalc should someone wish to use the expressions across multiple platforms.

-- Update --

I have created a parser for C# with plans to also implement it for Java and Swift over the next few months. This would mean that you can evaluate the expressions on multi-platforms without the need for tweaking per platform.

While Java and Swift was planned it never made it in to a fully fledge release. Instead there is now support for .NET Standard enabling support for Xamarin apps.

-- End update --

Expressive is the tool and it is available at: GitHub or Nuget.

The site has a fair amount of documentation on it but to prevent link rot here is an example on how to use it:

Variable support

var expression = new Expression("1 * [variable]");
var result = expression.Evaluate(new Dictionary<string, object> { ["variable"] = 2);

Functions

var expression = new Expression("sum(1,2,3,4)");
var result = expression.Evaluate();

It was designed to match NCalc as best as possible however it has added support for things like a 'null' keyword.

self promotion here i wrote aa generic parser generator for c# https://github.com/b3b00/csly you can find an expression parseras example on my github. you may need to customize it to fit your needs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!