![](/img/trans.png)
[英]how to write regular expression to validate a string using regex in 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.