文章关注两种注释
--类型和/* */类型
大概用例有这么几种
-- comments
select col from t1
/*
comments
*/
select col from t1
针对这两种情况比较简单:
public class RemoveSqlCommentHandler implements Handler {
@Override
public String processSql(String sql) {
final String[] commentPatterns = new String[] { "--[^\r\n]*", "/\\*[\\s\\S]*?\\*/" };
for (String commentPattern : commentPatterns) {
sql = sql.replaceAll(commentPattern, "");
}
return sql;
}
}
当然还有复杂一点的情况:
/*
-- comments */
可以稍微修改一下:
public class RemoveSqlCommentHandler implements Handler {
@Override
public String processSql(String sql) {
final String[] commentPatterns = new String[] { "--(?!.*\\*/).*?[\r\n]", "/\\*(.|\r|\n)*?\\*/" };
for (String commentPattern : commentPatterns) {
sql = sql.replaceAll(commentPattern, "");
}
return sql;
}
}
4.还有在查询的列中:
select col from t1 where name = '-- comments \n comments \n /* \n comments */'
则可以进一步修改成,替换匹配-- /* */ 这种,且不匹配在列中的
sql.replaceAll("(?ms)('(?:''|[^'])*')|--.*?$|/\\*.*?\\*/","$1")