在分隔符';'之间提取sql语句使用python RE

时间:2017-09-25 14:26:46

标签: python sql regex

我有一个带有以下语句的SQL文件,需要提取该语句

(t m) a

下面是python代码,它提取sql语句并计算SELECT关键字在语句中出现的次数

select * from customers;

select count(*) from customers;

select a.cust_name,sum(b.revenue) from
customers a join revenue_tab b 
on a.c_id=b.c_id
group by a.cust_name;

但结果字典看起来像这样

import re

query = {}

def GetTheStatements():
    with open('dummy.sql') as fp:
      for result in re.findall('(.*?);', fp.read(), re.S):
          count_select = sum(1 for x in re.finditer(r"\bselect\b", result))
          q = {result :{ 'count_select': count_select}}
          query.update(q)
    print query

GetTheStatements()

如何在正则表达式中获取语句时有时(\ n)从中删除换行符(\ n)?

1 个答案:

答案 0 :(得分:1)

你在哪里,

{{1}}

你可以替代,

{{1}}