Recursive logic for parsing string into complex boolean?

那年仲夏 提交于 2019-12-12 03:46:50

问题


I'm sure this has been done before, I just can't find it.

I need to turn something like, "((A OR B) AND C) OR D" into a database query for an attribute. Specifically I'm using Ruby Sequel. Can anyone point me at an example or utility or something that will keep me from reinventing the wheel?


回答1:


You can define a grammar using ANTLR and automatically generate a Ruby parser for those type of strings. ANTLR is a parser generator and it allows you to define a grammar for a language (such as a the boolean language that you described).

After parsing, you can specify what actions need to be taken to build the desired data structure (in your case a tree data structure that captures the structure of the query).

This is not particularly a Ruby problem as ANTLR can also generate parsers for other languages. In your case it would produce a Ruby parser that you can integrate into your application to parse the strings and to produce the data structure that you need.



来源:https://stackoverflow.com/questions/12167613/recursive-logic-for-parsing-string-into-complex-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!