有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用于以编程方式删除所有注释的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 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();
}

但它不起作用(评论没有被删除)


共 (1) 个答案

  1. # 1 楼答案

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

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

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

    regex101 for demo

    在Java代码中,这将是:

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

    警告:它不识别字符串文本,并且字符串文本中的/*//不会启动Java注释。然而,这个正则表达式将认为它是一个正则表达式,并从字符串文本中删除内容(以及其他内容)


    展开的版本是:

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

    给定的文本没有明显的差异。如果三行注释的长度为3000个字符,则展开的版本稍微快一点,但除非您正在做10000个替换,否则不足以引起注意,因此我会考虑这种过早的优化。p>