Python 从多行中提取特定字符串

我有一个 sql 文本,我想把其中的 sql 逐个提取出来

文本例如:

select xxxx from aaaa where bbb=123;
select yyy from
aaaa where
 bbb=123;
…
…

每一个 sql 都是以 select 开始,; 分号结束。一个 SQL 可以是一行,也可以是多行
请教各位专家,这个在 Python3 中如何高效的实现?

阅读 6.6k
3 个回答

re.compile(r"select.*?from.*?where.*?;", re.S|re.M)

def get_txt_sql(file_path):
    with open(file_path) as f:
        data = f.read()
        return data.split(';')
# -*- coding:utf-8 -*-

sqls = []

def get_txt_sql(file_path):
    with open(file_path) as f:
        with_aline = ""
        for line in f:
            with_aline += " " + line.rstrip("\n")
            if with_aline.endswith(";\n") or with_aline.endswith(";"):
                sqls.append(with_aline.strip("\n").strip())
                with_aline = ""


if __name__ == "__main__":
    get_txt_sql("./sql.txt")
    print(sqls)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题