【问题标题】:Regex to extract info from SQL query正则表达式从 SQL 查询中提取信息
【发布时间】:2010-08-25 05:27:52
【问题描述】:

由于我是 REGEX 的新手,我无法解决以下问题。

请分享一些与解析器相关的链接,以便我学习。

我在解决 SQL 语句下面的 int 时遇到问题。 它的更多行添加到之前的 INPUT 中。

请帮我解决这个问题。

DECLARE
numerator   NUMBER;
BEGIN
SELECT x, y INTO numerator, denominator FROM result_table, s_Table
WHERE sample_id = 8;
the_ratio := numerator/denominator;
IF the_ratio > lower_limit THEN
INSERT INTO 
ratio VALUES (table, coloum);
ELSE
INSERT INTO onemoreTable VALUES (table, -1);
END IF;
COMMIT;
delete from     --some comment
xyz where id=17;
EXCEPTION
WHEN ZERO_DIVIDE THEN
INSERT INTO ratio VALUES (table, 0);
COMMIT;
WHEN OTHERS THEN
ROLLBACK;
END;

输出:

SELECT from: result_table, s_Table
INSERT into: ratio
INSERT into: onemoreTable
DELETE from: xyz
INSERT into: ratio

【问题讨论】:

  • 偷偷摸摸,那里有评论。对于真正的 SQL,有更复杂的场景,您可能需要一个 SQL 解析器。这到底是什么语言?
  • 我同意 Kobi 的观点,除非你能保证非常基本的查询,否则你可能最好获得一个合适的 SQL 解析器。

标签: sql regex text-extraction


【解决方案1】:

这是一个使用正则表达式的基于 Perl 的解决方案:

$input =~s/--.*?\n//g; # delete the comments.
$input =~s/\s+/ /g; # replace multiple white space with single space.
while($input=~m/((?:insert into)|(?:delete from)) (\w+)/ig) { 
        print "$1 : $2\n";    
}

解析 SQL 的正确方法是使用解析器而不是使用正则表达式。

【讨论】:

  • 感谢 codadict 您的解决方案对我帮助很大。
猜你喜欢
  • 2013-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多