希望有人能幫助我解決這個問題!Java正則表達式,用於從字符串中刪除SQL註釋
我有一個SQL文件看起來像這樣:
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');
*/
我已經BUIT在啓動時使用此函數初始化一個MySQL數據庫的Web應用程序:
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);
}
}
(此功能被發現作者,請原諒我不引用你的名字,我失去了它!)
只要沒有SQL註釋塊,它就可以完美工作。
copyToString()
函數基本上做它所說的。 我現在想要的是構建一個正則表達式,它將從字符串中刪除塊註釋。我只在文件中有塊註釋/* */
,沒有--
。
我迄今爲止嘗試:
mySb = mySb.replaceAll("/\\*.*\\*/", "");
不幸的是,我不是在正則表達式的很好...
我得到的「匹配的字符串看起來像/* comment */ real statement /* another comment*/
」所有的煩惱等等...
你需要在你的正則表達式中使用惰性運算符'?' – Gabber 2012-04-19 10:37:37