如何用Java程序删除sql脚本中的注释
谢谢 问题点数:50、回复次数:7Top
1 楼treeroot(旗鲁特)回复于 2005-01-19 18:29:52 得分 10
String s="select * from table --comment\n insert into --comment";
String ss=s.replaceAll("--.+[\n]?","\n");Top
2 楼TinyJimmy(Jimmy)回复于 2005-01-19 19:53:22 得分 10
扫面文件, 如果以--开始, 删除从开始位置到改行结束的内容Top
3 楼chn217(天涯)回复于 2005-01-20 09:29:07 得分 0
那/**/中的注释如何删除?Top
4 楼chn217(天涯)回复于 2005-01-20 09:29:25 得分 0
各位帮帮忙啊Top
5 楼treeroot(旗鲁特)回复于 2005-01-20 09:41:06 得分 30
s=s.replaceAll("/\\*.+?\\*/","");Top
6 楼chn217(天涯)回复于 2005-01-20 09:43:43 得分 0
楼上写的无法匹配多行的注释
比如:
/*sssfasdf
sss
*/
因为.不能匹配\r\nTop
7 楼chn217(天涯)回复于 2005-01-20 12:22:40 得分 0
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
* @author fisher
*
* <pre>
*
* Title: SQLCommentFilter.java
*
* Description: 删除SQL脚本中的注释
*
* </pre>
*/
public class CommentFilter {
private boolean inMultiLineComment = false;
/**
* Filter out multiLine comments.
*/
private String multiLineCommentFilter(String line) {
StringBuffer buf = new StringBuffer();
int index;
if (inMultiLineComment && (index = line.indexOf("*/")) > -1) {
inMultiLineComment = false;
if (line.length() > index + 2) {
buf.append(inlineCommentFilter(line.substring(index + 2)));
}
return buf.toString();
} else if (inMultiLineComment) {
return "";
} else if ((index = line.indexOf("/*")) > -1) {
inMultiLineComment = true;
buf.append(inlineCommentFilter(line.substring(0, index)));
return buf.toString();
} else {
return inlineCommentFilter(line);
}
}
/**
* Filter inline comments
*/
private String inlineCommentFilter(String line) {
if (line == null || line.equals("")) {
return "";
}
return line.replaceAll("--.*", "");
}
private static void printUsage() {
System.out.println("Usage:java CommentFilter src_shell_file dest_shell_file");
}
public static void main(String[] args) throws IOException {
if (args.length != 2) {
printUsage();
System.exit(-1);
}
CommentFilter cf = new CommentFilter();
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(args[0])));
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(args[1])));
String line = null;
while ((line = reader.readLine()) != null) {
String filterLine = cf.multiLineCommentFilter(line);
if (filterLine.trim().equals(""))
continue;
writer.write(filterLine);
writer.newLine();
}
}
}Top




