C# 如何将字符串转换为BinaryExpression对象?

C# 如何将字符串转换为BinaryExpression对象?,c#,.net,expression,C#,.net,Expression,假设我们有如下字符串: string s1 = "a < 5"; string s2 = "b >= 7"; string s3 = "c <= 8"; ... string s4 = "a< 5" // no space between 'a' and '<' string s5 = "b>=9" // no space at all string s6 = "c <=7" // no space betwen '<=' and '7'

假设我们有如下字符串:

string s1 = "a < 5";
string s2 = "b >= 7";
string s3 = "c <= 8";
...
string s4 = "a< 5"  // no space between 'a' and '<'
string s5 = "b>=9"  // no space at all
string s6 = "c <=7"  // no space betwen '<=' and '7'
我创建了以下方法:

BinaryExpression ConvertStringToBinaryExpression( string exp )
{
  string[] s = exp.Split( ' ' );
  string param = s[ 0 ];
  string comparison = s[ 1 ];
  int constant = int.Parse( s[ 2 ] );
  if ( comparison == "<" )
    return Expression.MakeBinary( ExpressionType.LessThan, Expression.Parameter( typeof ( int ), param ), Expression.Constant( constant, typeof ( int ) ) );
  else if ( comparison == "<=" )
    return Expression.MakeBinary( ExpressionType.LessThanOrEqual, Expression.Parameter( typeof ( int ), param ), Expression.Constant( constant, typeof ( int ) ) );
  else if ( comparison == ">" )
    return Expression.MakeBinary( ExpressionType.GreaterThan, Expression.Parameter( typeof ( int ), param ), Expression.Constant( constant, typeof ( int ) ) );
  else if ( comparison == ">=" )
    return Expression.MakeBinary( ExpressionType.GreaterThanOrEqual, Expression.Parameter( typeof ( int ), param ), Expression.Constant( constant, typeof ( int ) ) );
  else
    throw new ArgumentException( "Invalid expression.", "exp" );
}
BinaryExpression ConvertStringToBinaryExpression(字符串表达式)
{
字符串[]s=exp.Split(“”);
字符串参数=s[0];
字符串比较=s[1];
int常量=int.Parse(s[2]);
如果(比较==“=”)
返回Expression.MakeBinary(ExpressionType.GreaterThanOrEqual,Expression.Parameter(typeof(int),param),Expression.Constant(Constant,typeof(int));
其他的
抛出新的ArgumentException(“无效表达式。”,“exp”);
}
但是,例如,如果我们有如下字符串,则上述方法无法正常工作:

string s1 = "a < 5";
string s2 = "b >= 7";
string s3 = "c <= 8";
...
string s4 = "a< 5"  // no space between 'a' and '<'
string s5 = "b>=9"  // no space at all
string s6 = "c <=7"  // no space betwen '<=' and '7'

string s4=“a<5”//a和“之间没有空格。使用正则表达式匹配某些类型的可能表达式(如果您有一个详尽且合理简短的可能表达式列表)。如果字符串与正则表达式不匹配,也要分析该字符串,以检查是否有任何意外的字符

编辑:regex和parse将帮助您在使用switch/if-else用例之前“清理”字符串


正如Harsha指出的那样,
regex
将使您的任务变得简单

Match m=Regex.Match("var4 <= 433",@"(?'leftOperand'\w+)\s*(?'operator'(<|<=|>|>=))\s*(?'rightOperand'\w+)");
m.Groups["leftOperand"].Value;//the varaible or constant on left side of the operator
m.Groups["operator"].Value;//the operator
m.Groups["rightOperand"].Value;//the varaible or constant on right side of the operator

Match m=Regex.Match(“var4您是否只使用>、=<作为比较运算符?但是如果字符串包含我在正则表达式中使用的任何空格y来匹配0个或更多空格,则返回false