繁体   English   中英

如何使用正则表达式或C#验证逻辑表达式

[英]How validate a logical expression using Regular expression Or C#

我需要验证逻辑表达式,例如

( ( var1 == var2 ) && ( var2 >= var4 || var1 > var5 ) )

( var1 < var2 ) 

( var1 == var2 || var3 != var4 )

每个大括号,变量和逻辑运算符均由单个SPACE分隔。

我需要一个正则表达式来解析它。

或告诉我一些逻辑,以使用C#进行验证。

谢谢。

您可以构建自己的解析器,也可以参见下文(在此处找到)。 您需要对它进行一些更改以考虑变量,但这并不难。 或者,在将它们传递给函数之前对其进行解析,或者将函数更改为除变量名和值之外的其他值。

    using System.CodeDom.Compiler;
    using Microsoft.CSharp;
    using System.Reflection;
    /// <summary>
    /// A simple function to get the result of a C# expression (basic and advanced math possible)
    /// </summary>
    /// <param name="command">String value containing an expression that can evaluate to a double.</param>
    /// <returns>a Double value after evaluating the command string.</returns>
    private double ProcessCommand(string command)
    {
        //Create a C# Code Provider
        CSharpCodeProvider myCodeProvider = new CSharpCodeProvider();
        // Build the parameters for source compilation.
        CompilerParameters cp = new CompilerParameters();
        cp.GenerateExecutable = false;//No need to make an EXE file here.
        cp.GenerateInMemory = true;   //But we do need one in memory.
        cp.OutputAssembly = "TempModule"; //This is not necessary, however, if used repeatedly, causes the CLR to not need to 
                                          //load a new assembly each time the function is run.
        //The below string is basically the shell of a C# program, that does nothing, but contains an
        //Evaluate() method for our purposes.  I realize this leaves the app open to injection attacks, 
        //But this is a simple demonstration.
        string TempModuleSource = "namespace ns{" +
                                  "using System;" +
                                  "class class1{" +
                                  "public static double Evaluate(){return " + command + ";}}} ";  //Our actual Expression evaluator

        CompilerResults cr = myCodeProvider.CompileAssemblyFromSource(cp,TempModuleSource);
        if (cr.Errors.Count > 0)
        {
            //If a compiler error is generated, we will throw an exception because 
            //the syntax was wrong - again, this is left up to the implementer to verify syntax before
            //calling the function.  The calling code could trap this in a try loop, and notify a user 
            //the command was not understood, for example.
            throw new ArgumentException("Expression cannot be evaluated, please use a valid C# expression");
        }
        else
        {
            MethodInfo Methinfo = cr.CompiledAssembly.GetType("ns.class1").GetMethod("Evaluate");
            return (double)Methinfo.Invoke(null, null);
        }
    } 

如果我这样做并且想作为正则表达式来创建,则我将创建一个多遍算法,每次遍历都消除经过验证的子情况(例如,用“ x”替换经过验证的“(x == y)”)

也许以以下内容开头: s/\\b\\w+ $op \\w+\\b/^^MAGICTOKEN^^/g

那么任何/ $ op /都是非法的。

然后集中在每个括号的循环中: s/\\(( [^\\)]+ )\\)/^^MAGICTOKEN^^/

当专注于$ 1时,减少: s/ $MAGICTOKRE $BOOL $MAGICTOKRE / ^^MAGICTOKEN^^ /循环运行reduce直到停止减少。 如果$1 ne " ^^MAGICTOKEN^^ " ,错误

在焦点循环之后,最有可能的$expression ne "^^MAGICTOKEN^^"将指示错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM