const regex = /(SELECT|DELETE)(?:\s*\/\*.*\*\/\s*?)*\s+FROM*\s+([^\s\/*;]+)?|(?:(?:(CREATE|ALTER|DROP)(?:(?:\s*\/\*.*\*\/\s*?)*\s+OR(?:\s*\/\*.*\*\/\s*?)*\s+(REPLACE))?)(?:\s*\/\*.*\*\/\s*?)*\s+TABLE(?:(?:\s*\/\*.*\*\/\s*?)*\s+IF(?:\s*\/\*.*\*\/\s*?)*\s+EXISTS)?|(UPDATE)|(ALTER)|(INSERT)(?:\s*\/\*.*\*\/\s*?)*\s+(?:INTO?))(?:\s*\/\*.*\*\/\s*?)*\s+([^\s\/*;]+)|(?:(REPLACE)(?:\s*\/\*.*\*\/\s*?)*\s+(?:INTO?))(?:\s*\/\*.*\*\/\s*?)*\s+([^\s\/*;]+)(?:\s*\/\*.*\*\/\s*?)*\s+([^\s\/*;]+)/gmi;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(SELECT|DELETE)(?:\\s*\\\/\\*.*\\*\\\/\\s*?)*\\s+FROM*\\s+([^\\s\\\/*;]+)?|(?:(?:(CREATE|ALTER|DROP)(?:(?:\\s*\\\/\\*.*\\*\\\/\\s*?)*\\s+OR(?:\\s*\\\/\\*.*\\*\\\/\\s*?)*\\s+(REPLACE))?)(?:\\s*\\\/\\*.*\\*\\\/\\s*?)*\\s+TABLE(?:(?:\\s*\\\/\\*.*\\*\\\/\\s*?)*\\s+IF(?:\\s*\\\/\\*.*\\*\\\/\\s*?)*\\s+EXISTS)?|(UPDATE)|(ALTER)|(INSERT)(?:\\s*\\\/\\*.*\\*\\\/\\s*?)*\\s+(?:INTO?))(?:\\s*\\\/\\*.*\\*\\\/\\s*?)*\\s+([^\\s\\\/*;]+)|(?:(REPLACE)(?:\\s*\\\/\\*.*\\*\\\/\\s*?)*\\s+(?:INTO?))(?:\\s*\\\/\\*.*\\*\\\/\\s*?)*\\s+([^\\s\\\/*;]+)(?:\\s*\\\/\\*.*\\*\\\/\\s*?)*\\s+([^\\s\\\/*;]+)', 'gmi')
const str = `DROP TABLE IF EXISTS tbl1; CREATE TABLE tbl1 ...
CREATE TABLE tbl1 ...
CREATE OR REPLACE TABLE tbl1 ...
INSERT /*some comment*/ INTO tbl2 ...
INSERT /*some comment*/ INTO tbl2 ...
UPDATE tbl3 SET col1 = ...
/*some garbage comments*/ UPDATE tbl3 SET col1 = ...
DELETE from tbl4 ...
select from select_table insert into table_ttt
alter table alter_table
#1 some optional statements like CREATE /*some comments*/ TABLE table_name everything else
#1 some optional statements like CREATE /*some comments*/ OR REPLACE TABLE table_name everything else
#2 some optional statements like INSERT /*some comments*/ INTO /*some comments*/ table_name
#3 some optional statements like UPDATE /*some comments*/ table_name everything else`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions