2016-04-07 1 views
1

私はコードでいくつかのテキストファイルを持っています。のJava正規表現は、プログラム

/*Comment here*/ 

public void start(Stage primaryStage) throws Exception{ 
    Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); 
    primaryStage.setTitle("First"); 
/*Comment here 
*and 
*here*/ 
    primaryStage.setScene(new Scene(root, 640, 480)); 
    primaryStage.show();//Comment this 
//and comment that 
} 

そして、それはそのように見えるように:ファイルを読み込み、それをすべて

public void delCommentAction(ActionEvent actionEvent) throws IOException { 
    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) { 
     bw.write(delComments(line)); 
    } 
    bw.close(); 
} 

を置き換えるしかし

public String delComments(String content){ 
    Pattern regex = Pattern.compile("/\\*.*?\\*/|/{2,}[^\\n]*", Pattern.MULTILINE); 
    Matcher matcher = regex.matcher(content); 
    String clean = content.replaceAll("(?s:/\\*.*?\\*/)|//.*", ""); 
    return clean; 
} 

方法:

public void start(Stage primaryStage) throws Exception{ 
    Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); 
    primaryStage.setTitle("First"); 
    primaryStage.setScene(new Scene(root, 640, 480)); 
    primaryStage.show(); 
} 

私はこれを試してみましたそれは動作しません(コメントは削除されませんでした)

+3

I'dが、これは、単一の正規表現のための多くにあると言います。むしろ、プロパーパーサーでコードを解析し、そのコメントを見つけようとするべきです。 – SomeJavaGuy

+0

あなたが試すことができ[ '" //.*[\r\n]*|(\"[^\\\\\"]*(?:\\\\.[^\\\\\"]* )* \ ")|/\\ * [^ *] * \\ * +([^/*] [* ^] * \\ * +)* /?" '](https://regex101.com/r/yU4aU5/1)。 –

答えて

1

としては、Java言語が正確にこれを行うための正規表現のためには複雑すぎるので、あなたは、完全なパーサーを使用する必要があり、コメントで提案されています。あなたは、いくつかの注意点とOKですしかし、もし、それが次の正規表現で行うことができます

(?s:/\*.*?\*/)|//.* 

regex101 for demoを参照してください。 Javaコードで

、それは次のようになります。

String clean = original.replaceAll("(?s:/\\*.*?\\*/)|//.*", ""); 

警告:それは文字列リテラルを認識しないと、文字列リテラル内の/*または//は、Javaのコメントを開始しません。しかし、この正規表現は1つだと思って、文字列リテラル(そしてそれ以上)からコンテンツを削除します。


巻かれていないバージョンがある:

String clean = original.replaceAll("/\\*[^*]*(?:\\*(?!/)[^*]*)*\\*/|//.*", ""); 

指定されたテキストには顕著な違い。 3行コメントの長さを3000文字にすると、アンロールされたバージョンはやや速くなりますが、10000以上の置換えをしない限り気付くほどではありません。

+0

'(?s:/ \ *。*?\ * /)'パターンは、非常に長いコメントでパフォーマンスの問題を引き起こす可能性があります。展開されたバージョンははるかに優れており、 'DOTALL'修飾子は必要ありません。 –

+0

@WiktorStribiżewアンロール版が追加されました。 – Andreas