简体   繁体   English

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

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

I tried using regular expression to filter the single and multi-line comments from my text file. 我尝试使用正则表达式来过滤我的文本文件中的单行和多行注释。 I am able to filter all the comments like 我可以过滤所有的评论

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

but I am not able to remove the following comment 但我无法删除以下评论

/*
sample
*/

This is my code: 这是我的代码:

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!");
    }
}
}

Please help me to solve this... 请帮我解决这个问题......

Thanks in advance. 提前致谢。

Using the javaparser you could solve it like shown in this PoC. 使用javaparser你可以解决它,就像在这个PoC中所示。

RemoveAllComments 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 used as an example input source TestClass.java用作示例输入源

/**
 * javadoc comment
 */
class TestClass {

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

    // line comment
    static interface Commentable {
    }

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

output to stdout (to store it in a file is up to you) 输出到stdout (将其存储在文件中取决于你)

class TestClass {

    static class Cafebabe {
    }

    static interface Commentable {
    }

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

Try this code 试试这个代码

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!");
  }
 }
}

I have given below code as input : 我已经给出了以下代码作为输入:

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

My output is : 我的输出是:

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

Since you read each line individually you can't apply a single regex to it. 由于您单独读取每一行,因此无法对其应用单个正则表达式。 Instead you'd have to look for single line comments ( //.* ) as well as start and end of multiline comments ( /\\*.* and .*\\*/ ). 相反,您必须查找单行注释( //.* )以及多行注释的开始和结束( /\\*.*.*\\*/ )。 If you find a multiline comment start then keep account of that and handle everything as a comment until you encounter the end match. 如果您发现多行评论开始,则记住该帐户并将所有内容作为评论处理,直到您遇到结束匹配为止。

Example: 例:

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

Edit: an important addition 编辑:一个重要的补充

In your question you're talking about text files which normally have a regular structure and thus you can apply my answer. 在您的问题中,您谈论的是通常具有常规结构的文本文件,因此您可以应用我的答案。

But, as you stated in the title, if the files contain Java code then you have a irregular problem domain, ie Java code. 但是,正如您在标题中所述,如果文件包含Java代码,那么您有一个不规则的问题域,即Java代码。 In that case you can't safely apply regex and should better use a Java parser. 在这种情况下,您无法安全地应用正则表达式,应该更好地使用Java解析器。

For more information have a look here: RegEx match open tags except XHTML self-contained tags Although this is about applying regex to HTML the same is true for applying regex on Java since both are irregular problem domains. 有关详细信息,请查看此处: RegEx匹配除XHTML自包含标记之外的开放标记虽然这是关于将正则表达式应用于HTML,但在Java上应用正则表达式也是如此,因为两者都是不规则的问题域。

Try out the following code: 试试下面的代码:

// 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);

It first reads the entire file into a string and then removes all comments from it. 它首先将整个文件读入一个字符串,然后从中删除所有注释。 The explaination of the regex could be found here: https://regex101.com/r/vK6lC4/3 可以在这里找到正则表达式的解释: https//regex101.com/r/vK6lC4/3

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

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