c# convert string expression to a boolean expression [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this questionIs it possible to convert a string expression into a boolean condition?
For example, I get the following string:
var b = "32 < 45 && 32 > 20"
I would like to create a bool
expression out of this and invoke it. The string representation is also flexible (to make it more fun), so it allows ||, &&, ()
.
Have a look at Flee (Fast Lightweight Expression Evaluator) on CodePlex.
I would use Irony, the .NET language kit. You could construct a simple grammar with Irony and then parse the string into executable command. There's a decent example of an arthmetic grammar in this tutorial and in the Expression Grammar Sample, its a pretty common request ;)
I definitely suggest using a proper compiler as opposed to Regex or a roll your own approach - it will be much more extensible if you ever want to add more rules.
If it follows all C# expression rules then compile it as dynamic code as per http://www.west-wind.com/presentations/dynamiccode/dynamiccode.htm
If you're dealing with relatively simple mathematical expressions then a straightforward implementation of the shunting-yard algorithm should do the trick.
Take a look at my library, Proviant. It's a .NET Standard library using the Shunting Yard algorithm to evaluate boolean expressions. You could also implement your own grammar.
I think creating an interpreter for this string would not take too long time.
http://www.industriallogic.com/xp/refactoring/implicitLanguageWithInterpreter.html
here you can find information about design that can be used to create it.
You could take a look at JINT (Javascript Interpreter for .NET) http://jint.codeplex.com/
精彩评论