Java regex to remove SQL comments from a string

java, regex, sql

Solution

Try

mySb = mySb.replaceAll("/\\*.*?\\*/", "");

(notice the `?` which stands for "lazy").

EDIT: To cover multiline comments, use this approach:

Pattern commentPattern = Pattern.compile("/\\*.*?\\*/", Pattern.DOTALL);
mySb = commentPattern.matcher(mySb).replaceAll("");

Hope this works for you.

Problem

Hope someone can help me out with this one ! I have a sql file that looks like this: ``` CREATE TABLE IF NOT EXISTS users( id INT UNSIGNED NOT NULL AUTO_INCREMENT, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, PRIMARY KEY (id), CONSTRAINT UNIQUE (firstname,lastname) ) ENGINE=InnoDB ; INSERT IGNORE INTO users (firstname,lastname) VALUES ('x','y'); /* INSERT IGNORE INTO users (firstname,lastname) VALUES ('a','b'); */ ``` I have buit a web application that initializes a mysql database at startup with this function: ``` public static void initDatabase(ConnectionPool pool, File sqlFile){ Connection con = null; Statement st = null; String mySb=null; try{ con = pool.getConnection(); mySb=IOUtils.copyToString(sqlFile); // We use ";" as a delimiter for each request then we are sure to have well formed statements String[] inst = mySb.split(";"); st = con.createStatement(); for(int i = 0; i<inst.length; i++){ // we ensure that there is no spaces before or after the request string // in order not to execute empty statements if(!inst[i].trim().isEmpty()){ st.executeUpdate(inst[i]); } } st.close(); }catch(IOException e){ throw new RuntimeException(e); }catch(SQLException e){ throw new RuntimeException(e); }finally{ SQLUtils.safeClose(st); pool.close(con); } } ``` (This function was found on the web. Author, please forgive me for not citing your name, I lost it !!) It works perfectly as long as there is not SQL comment blocks. The `copyToString()` function basically does what it says. What I would like now is build a regex that will remove block comments from the string. I only have block comments `/* */` in the file, no `--`. What I have tried so far: ``` mySb = mySb.replaceAll("/\\*.*\\*/", ""); ``` Unfortunatly, I'm not very good at regex... I get all the troubles of "The matched string look something like `/* comment */ real statement /* another comment*/` " and so on...

Original source