2016-04-03 13 views
0

私は次のように、ファイル内のコメントを削除する必要があります。削除コメントのJava

/* this*/ 
/*this 
* 
* 
*/ 
//And this 

、別のファイルに書き込みます。

String line = null; 
    FileReader fileReader = 
      new FileReader(filePath); 
    BufferedReader bufferedReader = 
      new BufferedReader(fileReader); 
    FileWriter fw = new FileWriter(filePathNoComm); 
    BufferedWriter bw = new BufferedWriter(fw); 
    while((line = bufferedReader.readLine()) != null) { 
     delComments(line); 
     bw.write(line); 
    } 
    bw.close(); 

を読んで

public String delComments(String input){ 
     String noComments = input.replaceAll("//.*|(\"(?:\\\\[^\"]|\\\\\"|.)*?\")|(?s)/\\*.*?\\*/", "$1 "); 
     return noComments; 

および方法が、それは動作しません: 私はこの正規表現を使用しました。 どうすればいいですか?コードスニペット以下

+1

を「それは動作しません」について詳しく説明し、あなたを含めることを忘れないでくださいステップバイステップのデバッグ観察。 –

+0

新しいテキストファイルがコメント付きで残っています。つまり、意味します。 –

+0

ステップバイステップのデバッグ観測を含めるのを忘れました。 –

答えて

0

試してみてください。

public static String delComments(String content){ 
    Pattern regex = Pattern.compile("/\\*.*?\\*/|/{2,}[^\\n]*", Pattern.DOTALL); 

    Matcher matcher = regex.matcher(content); 
    return matcher.replaceAll(""); 
} 

それはすべてのコメントを削除する必要があります。

私はサンプル入力ファイルがあります:掃除取得した後

package com.company; 

/** 
* Created by XXX on 4/3/16. 
*/ 

public class Test { 
    // Will fix it later 

    int x = 0; // declaration. 
} 

を、それが放出されます:

package com.company; 


public class Test { 


    int x = 0; 
} 
関連する問題