假设我们有类似的字符串:
string s1 = "a < 5";
string s2 = "b >= 7";
string s3 = "c <= 8";
...
我想将这些字符串转换为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 ) ) );
我创建了以下方法:
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" );
}
但是,如果我们有类似的字符串,则上述方法无法正常工作:
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'
使其更加强大和可靠的最简单方法是什么?
答案 0 :(得分:2)
使用正则表达式匹配某些类型的可能表达式(如果您有可能的表达式的详尽且相当短的列表)。如果字符串与正则表达式不匹配,也要解析字符串,以检查是否有任何意外的字符。
编辑:正则表达式和解析将帮助您“清理”字符串,然后才能使用switch / if-else案例。
http://www.c-sharpcorner.com/UploadFile/prasad_1/RegExpPSD12062005021717AM/RegExpPSD.aspx
答案 1 :(得分: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