Are there any good tutorials that describe how to use ANTLR to parse boolean search strings

淺唱寂寞╮ 提交于 2019-12-11 05:38:58

问题


I need to parse a boolean search string of keywords and operators into a SQL query to be executed from C# code. I think something like ANTLR is what I need for this task, but I'm not sure how to do it.

Are there any good tutorials on how to do this? Or maybe I need a different tool?

An example of what I mean is below. The only operators I need are AND and OR. I would also like to be able to use parenthesis.

input expression: (blue AND green) OR yellow

output:

SELECT * FROM table WHERE (CONTAINS(Description, "blue") AND CONTAINS(Description, "green")) OR >CONTAINS(Description, "yellow"

If possible I would also like to support implicit AND insertion. So the default operator if none is specified is AND.

input : green (blue OR yellow)

output: SELECT * FROM table WHERE CONTAINS(Description, "green") AND (CONTAINS(Description, "blue") OR >CONTAINS(Description, "yellow"))


回答1:


I'd probably do this with straight text processing. Essentially what you want to do is take the original expression, pull out all the colors and replace them with the CONTAINS clause. In pseudocode:

list of tokens = split input expression into tokens separated by spaces
foreach token in tokens
    if token is not keyword
        text = "CONTAINS(Description, \"" + token + "\")"
    else 
        text = token

    output = output + text
end

Where the keywords are "(", "AND", etc. You then just put the output in your SQL statement

< insert warning about SQL injection attacks here >



来源:https://stackoverflow.com/questions/1209005/are-there-any-good-tutorials-that-describe-how-to-use-antlr-to-parse-boolean-sea

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