Comment detail

コメントの削除 (Nested Flatten)

一番のりを狙って書きました。起動パラメータに与えられたJavaのソースファイルからコメントを削除し、".out" 拡張子つきのファイルに書き込みます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.regex.*;
import java.io.*;

public class Decomment {

    static final Pattern COMMENT1 = Pattern.compile("/\\*.*?\\*/", Pattern.DOTALL);
    static final Pattern COMMENT2 = Pattern.compile("//.*");
    
    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(System.getProperty("line.separator"));
            }
            String s1 = COMMENT1.matcher(sb).replaceAll("");
            String result = COMMENT2.matcher(s1).replaceAll("");
            w.write(result);
            w.close();
        }
    }
}

文字列リテラルに対応していませんでした。あわてると駄目ですね。

文字列リテラル対応版です。

 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
import java.util.regex.*;
import java.io.*;

public class Decomment {
    static final String LITERAL = "\"(?:\\\\.|[^\"])*\"";
    static final String COMMENT1 = "(?s:/\\*.*?\\*/)";
    static final String COMMENT2 = "//.*";
    static final Pattern DECOM_PAT = Pattern.compile("(" + LITERAL + ")|" + 
            COMMENT1 + "|" + COMMENT2);
    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);
            }
            String result = DECOM_PAT.matcher(sb).replaceAll("$1");
            w.write(result);
            w.close();
        }
    }
}

Index

Feed

Other

Link

Pathtraq

loading...