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

Set*_*o N 5 .net c# expression

假设我们有以下字符串:

string s1 = "a < 5";
string s2 = "b >= 7";
string s3 = "c <= 8";
...
Run Code Online (Sandbox Code Playgroud)

我想将这些字符串转换为类似于我们使用的BinaryExpression对象:

  BinaryExpression b1 = Expression.MakeBinary( ExpressionType.LessThan, Expression.Parameter( typeof( int ), "a" ), Expression.Constant( 5, typeof( int ) ) );
  BinaryExpression b2 = Expression.MakeBinary( ExpressionType.GreaterThanOrEqual, Expression.Parameter( typeof( int ), "b" ), Expression.Constant( 7, typeof( int ) ) );
  BinaryExpression b3 = Expression.MakeBinary( ExpressionType.LessThanOrEqual, Expression.Parameter( typeof( int ), "c" ), Expression.Constant( 8, typeof( int ) ) );
Run Code Online (Sandbox Code Playgroud)

我创建了以下方法:

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" );
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我们有类似的字符串,则上述方法无法正常工作:

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'
Run Code Online (Sandbox Code Playgroud)

什么是使其更加强大和可靠的最简单方法?

Ani*_*dha 2

正如 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
Run Code Online (Sandbox Code Playgroud)