コード圧縮
Posted feedbacks - Java
コメント #6548 を改造して、全てのコメントを除いて空白と改行を1個にまとめるプログラムにしました。
空白は削除できる場合もあるのですが、意味が変わる場合が考えられるために1個は残してあります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import java.util.regex.*;
import java.io.*;
public class Decomment2 {
static final String LITERAL = "(?:\"(?:\\\\.|[^\"])*\")|(?:\'(?:\\\\.|[^\'])*\')";
static final String COMMENT1 = "(?s:/\\*.*?\\*/)";
static final String COMMENT2 = "//.*";
static final String SPACES = "\\s+";
static final Pattern DECOM_PAT = Pattern.compile("(" + LITERAL + ")|((" +
COMMENT1 + "|" + COMMENT2 + "|" + SPACES + ")+)");
static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static void main(String[] args) throws IOException {
for (String name : args) {
BufferedReader r = new BufferedReader(new FileReader(name));
FileWriter w = new FileWriter(name + ".out");
StringBuilder sb = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
sb.append(line).append(LINE_SEPARATOR);
}
Matcher m = DECOM_PAT.matcher(sb);
StringBuffer replace = new StringBuffer();
while (m.find()) {
if (m.group(2) != null && m.group(2).length() > 0) {
m.appendReplacement(replace, " ");
} else {
m.appendReplacement(replace, "$1");
}
}
m.appendTail(replace);
w.write(replace.toString());
w.close();
}
}
}
|


sweetie089 #6664() Rating-6/10=-0.60
[ reply ]