-1

如何?但是我需要一个解析器,它只解析一次字符串并且有一个像这样的接口

Func<double,double> MathEvaluator(string input)

或者像这样

LambdaExpression MathEvaluator(string input)

它存在吗?

4

3 回答 3

2

我想参考这个线程,引用由RickOliverMax的答案提供的结果。

您需要考虑,哪个最符合您的要求。例如,Math Parser .NET 支持^幂,而其他的则不支持。

于 2013-02-28T19:44:04.790 回答
1

所以我做了一个库,如果你愿意,你可以使用它,我认为它已经足够好了。有一些正则表达式,将 a^b 之类的结构替换为 Math.Pow(a,b) 等。它可能会更好,但这对我来说很难,但我正在努力。

using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using Microsoft.CSharp;

namespace MathEvalNS
{
public class MathEvaluator
{
    private readonly Delegate parsedFunction;
    private readonly string normalized;
    public double Invoke(double x)
    {
        if (parsedFunction == null)
            throw new NullReferenceException("No function to invoke");
        return (double)parsedFunction.DynamicInvoke(x);
    }
    private const string Begin =
        @"using System;
namespace MyNamespace
{
    public static class LambdaCreator 
    {
        public static Func<double,double> Create()
        {
            return (x)=>";
        private const string End = @";
        }
    }
}";

    public MathEvaluator(string input)
    {
        normalized = Normalize(input);
        var provider = new CSharpCodeProvider();
        var parameters = new CompilerParameters { GenerateInMemory = true };
        parameters.ReferencedAssemblies.Add("System.dll");
        CompilerResults results = provider.CompileAssemblyFromSource(parameters, Begin + normalized + End);
        try
        {
            var cls = results.CompiledAssembly.GetType("MyNamespace.LambdaCreator");
            var method = cls.GetMethod("Create", BindingFlags.Static | BindingFlags.Public);
            parsedFunction = (method.Invoke(null, null) as Delegate);
        }
        catch (FileNotFoundException)
        {
            throw new ArgumentException();
        }
    }

    private string Normalize(string input)
    {
        return input.ReplaceMath().ReplacePow().ReplaceMultipling().ReplaceToDoubles();
    }
}

public static class StringHelper
{
    public static string ReplaceMultipling(this string input)
    {
        return Regex.Replace(input, @"(\d+)(x)", @"$1*$2");
    }

    public static string ReplacePow(this string input)
    {
        var result = input.ReplacePow(@"(\d*x)\^(\d+\.?\d*)");
        return result.ReplacePow(@"\(([^\^]+)\)\^(\d+\.?\d*)");
    }

    private static string ReplacePow(this string input, string toReplace)
    {
        return Regex.Replace(input, toReplace, "Math.Pow($1,$2)");
    }

    public static string ReplaceToDoubles(this string input)
    {
        return Regex.Replace(input, @"(\d+)(?:[^\.]\d+)", "$1.0");
    }

    public static string ReplaceMath(this string input)
    {
        return
            input.ReplaceMath("sin", @"Math.Sin")
                 .ReplaceMath("cos", @"Math.Cos")
                 .ReplaceMath("ctg", @"1.0/Math.Tan")
                 .ReplaceMath("tg", @"Math.Tan");
    }

    private static string ReplaceMath(this string input, string name, string dotNetName)
    {
        return Regex.Replace(input, name, dotNetName, RegexOptions.IgnoreCase);
    }
}
}
于 2013-03-01T05:52:44.470 回答
0

我有一个 MathParser:http: //github.com/MathewSachin/MathParser

我希望你想要的可以这样完成:

Fuc<double, double> Parse(string Expression)
{
    MathParser P = new MathParser();
    Variable V = new Variable("x", 0); // The Variable you use with default value
    P.Variables.Add(V);

    P.Parse(Expression);

    return (Input) =>
        {
            V.Value = Input;
            return P.Evaluate();
        }
}

我唯一担心的是垃圾收集。

于 2015-10-16T08:48:00.550 回答