用于在文本文件中拆分 SQL 查询的正则表达式

问题描述

我有以下 sql 文件

  CREATE TABLE TABLE1
   (    ID INTEGER,);
   
  CREATE TABLE TABLE2
   (    ID INTEGER,

我想提取查询。我使用以下代码执行此操作:

try {
    Path sqlPath = FileSystems.getDefault().getPath("C:/Users/myPC/Desktop/create_tables.sql");
    String sql = new String(Files.readAllBytes(sqlPath));
    commands = sql.split("\n\n");
    System.out.println(commands.length) //== 1 while it should be 2;
} catch (Exception e) {
    System.out.println(e.getMessage());
    return;
}

但我明白了:

解析异常预期的EOF或CREATE,...

在这种情况下,正则表达式分隔符应该是什么?

解决方法

使用

String[] commands = sql.split("(?<=;)\\s+");

regex proof

说明

--------------------------------------------------------------------------------
  (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
    ;                        ';'
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  \s+                      whitespace (\n,\r,\t,\f,and " ") (1 or
                           more times (matching the most amount
                           possible))