是否有任何好的教程描述如何使用 ANTLR 来解析布尔搜索字符串 [英] Are there any good tutorials that describe how to use ANTLR to parse boolean search strings

查看:19
本文介绍了是否有任何好的教程描述如何使用 ANTLR 来解析布尔搜索字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将关键字和运算符的布尔搜索字符串解析为要从 C# 代码执行的 SQL 查询.我认为这个任务需要像 ANTLR 这样的东西,但我不知道该怎么做.

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?

我的意思的一个例子如下.我需要的唯一运算符是 AND 和 OR.我也希望能够使用括号.

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

输出:

选择 *发件人表WHERE (CONTAINS(Description, blue") AND CONTAINS(Description, green")) OR >CONTAINS(Description, yellow")

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

如果可能,我还想支持隐式 AND 插入.所以如果没有指定,默认的运算符是 AND.

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)

输出:选择 *发件人表WHERE CONTAINS(Description, "green") AND (CONTAINS(Description, "blue") OR >CONTAINS(Description, "yellow"))

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

推荐答案

我可能会用直接文本处理来做到这一点.基本上你想要做的是获取原始表达式,拉出所有颜色并用 CONTAINS 子句替换它们.在伪代码中:

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

其中关键字是("、AND"等.然后您只需将输出放在 SQL 语句中

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

<在此处插入有关 SQL 注入攻击的警告 >

< insert warning about SQL injection attacks here >

这篇关于是否有任何好的教程描述如何使用 ANTLR 来解析布尔搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆