使用正则表达式解析select语句(用于自定义SQL解析器) [英] Parsing select statement with regex (for custom SQL parser)
问题描述
我这样做是出于教学目的(建立教学数据库;像成熟的数据库一样建立它的一部分;这是一个非常简单的查询解析器.)
I am doing this for didactic purposes (building a teaching database; building parts of it just as full-blown databases have it; this is for a very simple query parser.)
我正在尝试使用正则表达式解析出简单的"select"语句.它适用于大多数简单的情况,但是我失去了平衡,只能在选择表之间留空格( from a,b; ),在from和终止符;之间允许无限制的空格.,并允许使用可选的限制器" where ",并且在与a,b where 和;
I am trying to parse out simple "select" statement using regex. It works for most simple cases, but I am losing it at the balance of allowing spaces between selection of tables (from a,b;), allowing unlimited spaces between from and terminator ;, and allowing for optional restrictor "where" and unlimited spaces between from a,b where and ;
这是正则表达式:
select\s(.*)\sfrom(.*)\s(where (.*))?\s;
这是示例查询:
select a.a,b.b,c from a,b where a.a = b.a;
select a.a,b.b,c from a,b;
select a.a,b.b,c from a,b ;
select a.a,b.b,c from a,b where a.a = b.a ;
可在 regex 101 上进行单元测试.
推荐答案
这将适用于提供的示例:select\s+(.*?)\s*from\s+(.*?)\s*(where\s(.*?)\s*)?;
This will work for the examples provided : select\s+(.*?)\s*from\s+(.*?)\s*(where\s(.*?)\s*)?;
查看此处: https://regex101.com/r/sBwpok/3
这篇关于使用正则表达式解析select语句(用于自定义SQL解析器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!