繁体   English   中英

如何编写一个java程序来过滤所有注释行并只打印java编码行?

[英]How to write a java program to filter all commented lines and print only java coding lines?

我尝试使用正则表达式来过滤我的文本文件中的单行和多行注释。 我可以过滤所有的评论

//it works
/*
* welcome
*/
/* hello*/

但我无法删除以下评论

/*
sample
*/

这是我的代码:

import java.io.*;
import java.lang.*;


class TestProg
{
public static void main(String[] args) throws IOException {
    removeComment();
}
static void removeComment() throws IOException
{
    try {
        BufferedReader br = new BufferedReader(new FileReader("d:\\data.txt"));
        String line;
        while((line = br.readLine()) != null){
            if(line.contains("/*") && line.contains("*/") || line.contains("//")) {

                System.out.println(line.replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)","")); 
            }
            else if(line.contains("/*") || line.contains("*") || line.contains("*/")) {

                continue;
            }
            else
                System.out.println(line); 
        }
        br.close();
    }

    catch(IOException e) {
        System.out.println("OOPS! File could not read!");
    }
}
}

请帮我解决这个问题......

提前致谢。

使用javaparser你可以解决它,就像在这个PoC中所示。

RemoveAllComments

import japa.parser.JavaParser;
import japa.parser.ParseException;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.Node;
import java.io.File;
import java.io.IOException;

public class RemoveAllComments {

    static void removeComments(Node node) {
        for (Node child : node.getChildrenNodes()) {
            child.setComment(null);
            removeComments(child);
        }
    }

    public static void main(String[] args) throws ParseException, IOException {
        File sourceFile = new File("Test.java");
        CompilationUnit cu = JavaParser.parse(sourceFile);
        removeComments(cu);
        System.out.println(cu.toString());
    }
}

TestClass.java用作示例输入源

/**
 * javadoc comment
 */
class TestClass {

    /*
     * block comment
     */
    static class Cafebabe {
    }

    // line comment
    static interface Commentable {
    }

    public static void main(String[] args) {
    }
}

输出到stdout (将其存储在文件中取决于你)

class TestClass {

    static class Cafebabe {
    }

    static interface Commentable {
    }

    public static void main(String[] args) {
    }
}

试试这个代码

import java.io.*;
import java.lang.*;

class Test {

 public static void main(String[] args) throws IOException {
 removeComment();
 }

 static void removeComment() throws IOException {
  try {
      BufferedReader br = new BufferedReader(new FileReader("d:\\fmt.txt"));
      String line;
      boolean comment = false;
      while ((line = br.readLine()) != null) {
      if (line.contains("/*")) {
          comment = true;
          continue;
      }
      if(line.contains("*/")){
          comment = false;
          continue;
      }
      if(line.contains("//")){
          continue;
      }
      if(!comment){
      System.out.println(line);
      }
    }
    br.close();
 }

 catch (IOException e) {
    System.out.println("OOPS! File could not read!");
  }
 }
}

我已经给出了以下代码作为输入:

package test;
public class ClassA extends SuperClass {
 /**
 * 
 */
    public void setter(){
    super.set(10);
    }
  /*  public void printer(){
    super.print();
    }
*/    
    public static void main(String[] args) {
//  System.out.println("hi");
    }    
}

我的输出是:

package test;
public class ClassA extends SuperClass {
    public void setter(){
    super.set(10);
    }
    public static void main(String[] args) {
    }    
}

由于您单独读取每一行,因此无法对其应用单个正则表达式。 相反,您必须查找单行注释( //.* )以及多行注释的开始和结束( /\\*.*.*\\*/ )。 如果您发现多行评论开始,则记住该帐户并将所有内容作为评论处理,直到您遇到结束匹配为止。

例:

boolean inComment = false;
while((line = br.readLine()) != null){
  //single line comment, remove everything after the first //
  if( line.contains("//") ) {
     System.out.println(line.replaceAll("//.*","")); 
  } 
  //start of multiline, remove everthing after the first /*
  else if( line.contains("/*") ) { 
    System.out.println(line.replaceAll("/\*.*","")); 
    inComment = true;
  }
  //end of multiline, remove everthing until the first */
  else if( line.contains("*/") {
    //note the reluctant quantifier *? which is necessary to match as little as possible 
    //(otherwise .* would match */ as well)
    System.out.println(line.replaceFirst(".*?\*/","")); 
    inComment = true;
  }
  //inside a multiline comment, ignore the entire line
  else if( inComment ) {
    continue;
  }

编辑:一个重要的补充

在您的问题中,您谈论的是通常具有常规结构的文本文件,因此您可以应用我的答案。

但是,正如您在标题中所述,如果文件包含Java代码,那么您有一个不规则的问题域,即Java代码。 在这种情况下,您无法安全地应用正则表达式,应该更好地使用Java解析器。

有关详细信息,请查看此处: RegEx匹配除XHTML自包含标记之外的开放标记虽然这是关于将正则表达式应用于HTML,但在Java上应用正则表达式也是如此,因为两者都是不规则的问题域。

试试下面的代码:

// Read the entire file into a string 
BufferedReader br = new BufferedReader(new FileReader("filename"));
StringBuilder builder = new StringBuilder();
int c;
while((c = br.read()) != -1){
    builder.append((char) c);
}
String fileData = builder.toString();


// Remove comments
String fileWithoutComments = fileData.replaceAll("([\\t ]*\\/\\*(?:.|\\R)*?\\*\\/[\\t ]*\\R?)|(\\/\\/.*)", "");
System.out.println(fileWithoutComments);

它首先将整个文件读入一个字符串,然后从中删除所有注释。 可以在这里找到正则表达式的解释: https//regex101.com/r/vK6lC4/3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM