Regular expression to extract SQL query

Vel*_*lth 5 java regex matcher

Is there a regex which extracts SQL queries from a string? I'm NOT interested to validate any SQL syntax, rather and only extracting a selection of SQL commands. This to parse a given SQL file/string in a flexible manner.

Given is the following SQL file/string example:

SELECT
    *
FROM
    test_table
WHERE
    test_row = 'Testing ; semicolon';

SELECT * FROM another_test_table;

INSERT INTO 
    table_name 
VALUES 
    (value1,'value which contains semicolon ;;;;',value3,...);
Run Code Online (Sandbox Code Playgroud)

Some pseudocode example would be: ^(UPDATE|SELECT|INSERT INTO)(.*)(;)$. In the future i'm looking to extend this with all (possible) commands.

  • Look for a starting match with either: (UPDATE|SELECT|INSERT|INTO)
  • Zero or more any character (including whitespaces and newlines)
  • Stop at ;, which delimits the SQL query.

Whenever this would be possible via a regex the following java code is able to extract all SQL commands:

final String regex = "LOOKING_FOR_THIS_ONE";
final Pattern p = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = p.matcher(content);

while (matcher.find()) {
  // matcher.group() now contains the full SQL command
}
Run Code Online (Sandbox Code Playgroud)

Thanks in advance!

Wal*_*lls 0

(?m)^(UPDATE|SELECT|INSERT INTO).*;$应该管用。这将扩展模式以匹配换行符。它应该能够循环并找到所有 SQL。

查看您提供的示例,它将匹配您的命令,直到;. 您可以在此处查看用于测试的示例。