簡體   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