简体   繁体   中英

removing single line SQL comments using java

How do you remove single line SQL comments froma single string using Java? I tried something like the following, but this doesnot seem to be fool-proof. Need a regex that will account for '--' characters when they appear as literals in select statements as in select '--hi' from dual.

   protected String removeSingleLineComments(String sql)
{

  Pattern pattern = Pattern.compile("--[^\r\n]*");
  Matcher matcher = pattern.matcher(sql);


  while(matcher.find()) {


      if((matcher.start()==0) || (matcher.start()>0 && sql.charAt(matcher.start()-1) != '\''))
  {
      sql =sql.replace(sql.substring(matcher.start(), matcher.end()), "").trim();


  }
  }
  return sql;

} 

正则表达式应该是: --.*$ ,以可移植的方式匹配行尾。

Pattern looks okay. Matcher is used as:

Pattern pattern = Pattern.compile("^(([^']+|'[^']*')*)--[^\r\n]*");
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
    matcher.appendReplacement(sb, "$1");
}
matcher.appendTail(sb);
return sb.toString();

The pattern does:

^((
    [^']+
|
    '[^']*'
)*)
--[^\r\n]*

Line start, repetition of either non-apostrophe chars or string literal. The extra parenthesis is to have $1 take the remaining SQL.

Just split the string by carriage return then split each line by "--":

  private static String removeInLineSQLComments(String sql) {
      StringBuilder stringBuilder = new StringBuilder();
      for (String line : sql.split("\n")) {
          stringBuilder.append(line.split("--")[0]).append("\n");
      }
      return stringBuilder.toString();
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM