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

时间:2011-05-20 06:37:16

标签: c# regex validation

我需要验证像<,p>这样的逻辑表达式

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

( var1 < var2 ) 

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

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

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

或者告诉我用C#验证这一点的逻辑。

感谢。

2 个答案:

答案 0 :(得分:0)

构建自己的解析器,或者参见下面的内容(找到here)。您需要稍微更改一下以考虑变量,但这不应该太难。要么在将它们传递给函数之前解析它们,要么将函数更改为变量名和值除外。

    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);
        }
    } 

答案 1 :(得分:0)

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

也许是以s/\b\w+ $op \w+\b/^^MAGICTOKEN^^/g

开头的事情

然后任何/ $ op /都是非法的。

然后专注于每个paren的循环:s/\(( [^\)]+ )\)/^^MAGICTOKEN^^/

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

在焦点循环之后,很可能$expression ne "^^MAGICTOKEN^^"表示错误。