469,592 Members | 2,030 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,592 developers. It's quick & easy.

How to evaluate a string expression to a boolean...

This is kind of a weird one and hard to find answers online because of the format of the question.

Essentially I want to be able to have a string that looks like this "True AND True AND True" and evaluate that to a boolean which in this case would be True. Another example would be "(True or False) AND True" would be True. The reason for this is that I have a form where the user has to build some logic in a graphical interface. I can evaluate the logic and create a string but I don't know how to evaluate the string. The problem is that they can also choose items such as OR\AND\NOT which is hard to account for in code.

BTW I am working in VB .Net.


HELP!!
Jan 24 '08 #1
2 4594
I think I have this figured out. I borrowed some C# code that is similar and converted to VB .Net. I still don't completely understand why it works but I have verified that it does.

Private Function Eval(ByVal expression As String) As Boolean
expression = expression.ToLower
expression = expression.Replace("false", "0")
expression = expression.Replace("true", "1")
expression = expression.Replace(" ", "")
Dim temp As String

Do
temp = expression
expression = expression.Replace("(0)", "0")
expression = expression.Replace("(1)", "1")
expression = expression.Replace("0and0", "0")
expression = expression.Replace("0and1", "0")
expression = expression.Replace("1and0", "0")
expression = expression.Replace("1and1", "1")
expression = expression.Replace("0or0", "0")
expression = expression.Replace("0or1", "1")
expression = expression.Replace("1or0", "1")
expression = expression.Replace("1or1", "1")
Loop While temp <> expression

If expression = "0" Then
Return False
End If
If expression = "1" Then
Return True
End If
Throw New ArgumentException("expression")
End Function

Usage Example:
Eval("(True or True or False) and True")

Returns True as a boolean
Jan 24 '08 #2
Plater
7,872 Expert 4TB
Sounds like you are creating a regular grammer for yourself.
Seems like a workable enough solution.
Jan 24 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by Bagger Vance | last post: by
22 posts views Thread by Paminu | last post: by
3 posts views Thread by Coco | last post: by
8 posts views Thread by No Such Luck | last post: by
3 posts views Thread by willempie | last post: by
4 posts views Thread by guiromero | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.