用于以编程方式删除所有注释的Java正则表达式

用于以编程方式删除所有注释的Java正则表达式,java,regex,Java,Regex,我有一些带有代码的文本文件 /*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.setSc

我有一些带有代码的文本文件

 /*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 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();
}
我试过这个:

 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 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();
}

但是它不起作用(注释没有被删除)

正如注释中所建议的那样,您应该使用完整的解析器,因为Java语言太复杂,正则表达式无法准确地完成这项工作

但是,如果您对一些注意事项没有异议,可以使用以下正则表达式来完成:

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

在Java代码中,这将是:

String clean=original.replaceAll((?s:/\\*.?\\*/)\124;/.*,“”);
警告:它不识别字符串文本,并且字符串文本中的
/*
/
不会启动Java注释。然而,这个正则表达式将认为它是一个正则表达式,并从字符串文本中删除内容(甚至更多)


展开版本为:

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

在给定的文本上没有明显的差异。如果三行注释的长度为3000个字符,则展开的版本稍微快一点,但除非您正在做10000个替换,否则不足以引起注意,所以我会考虑这种过早的优化。您应该尝试使用propper解析器解析代码并查找注释。您可以尝试。
(?s:/\*.*?\*/)
模式可能会导致注释过长的性能问题。展开版本更好,并且不需要
DOTALL
修改器。@WiktorStribiżew添加了展开版本。