Java:从字符串中删除注释

时间:2011-12-24 21:03:50

标签: java string comments

我想做一个获取字符串的函数,如果它有内联注释,它会删除它。我知道这听起来很简单,但我想确保我这样做是正确的,例如:

private String filterString(String code) {
  // lets say code = "some code //comment inside"

  // return the string "some code" (without the comment)
}

我想了两种方法:随意提出建议

  1. 迭代字符串并找到双内联括号并使用子字符串方法。
  2. 正则表达方式..(我不太确定回合)
  3. 你能告诉我最好的方法是什么,并告诉我应该怎么做? (请不要建议太高级的解决方案)

    编辑:这可以用Scanner对象以某种方式完成吗? (我还是使用这个对象)

8 个答案:

答案 0 :(得分:7)

如果您希望更高效的正则表达式真正匹配所有类型的注释,请使用以下注释:

replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)",""));

来源:http://ostermiller.org/findcomment.html

编辑:

另一种解决方案,如果你不确定使用正则表达式,那就是设计一个如下的小型自动机:

public static String removeComments(String code){
    final int outsideComment=0;
    final int insideLineComment=1;
    final int insideblockComment=2;
    final int insideblockComment_noNewLineYet=3; // we want to have at least one new line in the result if the block is not inline.

    int currentState=outsideComment;
    String endResult="";
    Scanner s= new Scanner(code);
    s.useDelimiter("");
    while(s.hasNext()){
        String c=s.next();
        switch(currentState){
            case outsideComment: 
                if(c.equals("/") && s.hasNext()){
                    String c2=s.next();
                    if(c2.equals("/"))
                        currentState=insideLineComment;
                    else if(c2.equals("*")){
                        currentState=insideblockComment_noNewLineYet;
                    }
                    else 
                        endResult+=c+c2;
                }
                else
                    endResult+=c;
                break;
            case insideLineComment:
                if(c.equals("\n")){
                    currentState=outsideComment;
                    endResult+="\n";
                }
            break;
            case insideblockComment_noNewLineYet:
                if(c.equals("\n")){
                    endResult+="\n";
                    currentState=insideblockComment;
                }
            case insideblockComment:
                while(c.equals("*") && s.hasNext()){
                    String c2=s.next();
                    if(c2.equals("/")){
                        currentState=outsideComment;
                        break;
                    }

                }

        }
    }
    s.close();
    return endResult;   
}

答案 1 :(得分:5)

执行此操作的最佳方法是使用正则表达式。 首先查找/**/个注释,然后删除所有//个commnets。例如:

private String filterString(String code) {
  String partialFiltered = code.replaceAll("/\\*.*\\*/", "");
  String fullFiltered = partialFiltered.replaceAll("//.*(?=\\n)", "")
}

答案 2 :(得分:3)

使用正则表达式替换在常量子字符串之前查找子字符串有点多。

您可以使用indexOf()来检查评论开始的位置,substring()来获取第一部分,例如:

String code = "some code // comment";
int    offset = code.indexOf("//");

if (-1 != offset) {
    code = code.substring(0, offset);
}

答案 3 :(得分:3)

只需使用String类中的 replaceAll 方法,并结合简单的正则表达式。这是如何做到的:

import java.util.*;
import java.lang.*;

class Main
{
        public static void main (String[] args) throws java.lang.Exception
        {
                String s = "private String filterString(String code) {\n" +
"  // lets say code = \"some code //comment inside\"\n" +
"  // return the string \"some code\" (without the comment)\n}";

                s = s.replaceAll("//.*?\n","\n");
                System.out.println("s=" + s);

        }
}

关键是这一行:

s = s.replaceAll("//.*?\n","\n");

正则表达式 //. *?\ n 匹配以 // 开头的字符串,直到该行的结尾。

如果您想要查看此代码,请转到此处:http://www.ideone.com/e26Ve

希望它有所帮助!

答案 4 :(得分:1)

@Christian Hujer已正确指出,如果评论发生在字符串中,则发布的许多或所有解决方案都会失败。

@LoïcGammaitoni建议他的自动机方法可以很容易地扩展到处理这种情况。这是扩展名。

enum State { outsideComment, insideLineComment, insideblockComment, insideblockComment_noNewLineYet, insideString };

public static String removeComments(String code) {
  State state = State.outsideComment;
  StringBuilder result = new StringBuilder();
  Scanner s = new Scanner(code);
  s.useDelimiter("");
  while (s.hasNext()) {
    String c = s.next();
    switch (state) {
      case outsideComment:
        if (c.equals("/") && s.hasNext()) {
          String c2 = s.next();
          if (c2.equals("/"))
            state = State.insideLineComment;
          else if (c2.equals("*")) {
            state = State.insideblockComment_noNewLineYet;
          } else {
            result.append(c).append(c2);
          }
        } else {
          result.append(c);
          if (c.equals("\"")) {
            state = State.insideString;
          }
        }
        break;
      case insideString:
        result.append(c);
        if (c.equals("\"")) {
          state = State.outsideComment;
        } else if (c.equals("\\") && s.hasNext()) {
          result.append(s.next());
        }
        break;
      case insideLineComment:
        if (c.equals("\n")) {
          state = State.outsideComment;
          result.append("\n");
        }
        break;
      case insideblockComment_noNewLineYet:
        if (c.equals("\n")) {
          result.append("\n");
          state = State.insideblockComment;
        }
      case insideblockComment:
        while (c.equals("*") && s.hasNext()) {
          String c2 = s.next();
          if (c2.equals("/")) {
            state = State.outsideComment;
            break;
          }
        }
    }
  }
  s.close();
  return result.toString();
}

答案 5 :(得分:0)

对于扫描仪,请使用分隔符,

分隔符示例。

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class MainClass {
  public static void main(String args[]) throws IOException {
FileWriter fout = new FileWriter("test.txt");
fout.write("2, 3.4,    5,6, 7.4, 9.1, 10.5, done");
fout.close();

FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
// Set delimiters to space and comma.
// ", *" tells Scanner to match a comma and zero or more spaces as
// delimiters.

src.useDelimiter(", *");

// Read and sum numbers.
while (src.hasNext()) {
  if (src.hasNextDouble()) {
    System.out.println(src.nextDouble());
  } else {
    break;
  }
}
fin.close();
  }
}

将标记化器用于普通字符串

标记生成器:

// start with a String of space-separated words
String tags = "pizza pepperoni food cheese";

// convert each tag to a token
StringTokenizer st = new StringTokenizer(tags," ");

while ( st.hasMoreTokens() )
{
  String token = (String)st.nextToken();
  System.out.println(token);
}

http://www.devdaily.com/blog/post/java/java-faq-stringtokenizer-example

答案 6 :(得分:0)

我为此创建了一个开源library (on GitHub),它名为CommentRemover,您可以删除单行和多行Java注释。

它支持删除或不删除TODO 它也支持JavaScript,HTML,CSS,属性,JSP和XML注释。

小代码片段如何使用它(有2种类型用法):

第一种方式是InternalPath

 public static void main(String[] args) throws CommentRemoverException {

 // root dir is: /Users/user/Projects/MyProject
 // example for startInternalPath

 CommentRemover commentRemover = new CommentRemover.CommentRemoverBuilder()
        .removeJava(true) // Remove Java file Comments....
        .removeJavaScript(true) // Remove JavaScript file Comments....
        .removeJSP(true) // etc.. goes like that
        .removeTodos(false) //  Do Not Touch Todos (leave them alone)
        .removeSingleLines(true) // Remove single line type comments
        .removeMultiLines(true) // Remove multiple type comments
        .startInternalPath("src.main.app") // Starts from {rootDir}/src/main/app , leave it empty string when you want to start from root dir
        .setExcludePackages(new String[]{"src.main.java.app.pattern"}) // Refers to {rootDir}/src/main/java/app/pattern and skips this directory
        .build();

 CommentProcessor commentProcessor = new CommentProcessor(commentRemover);
                  commentProcessor.start();        
  }

第二种方式ExternalPath

 public static void main(String[] args) throws CommentRemoverException {

 // example for externalPath

 CommentRemover commentRemover = new CommentRemover.CommentRemoverBuilder()
        .removeJava(true) // Remove Java file Comments....
        .removeJavaScript(true) // Remove JavaScript file Comments....
        .removeJSP(true) // etc..
        .removeTodos(true) // Remove todos
        .removeSingleLines(false) // Do not remove single line type comments
        .removeMultiLines(true) // Remove multiple type comments
        .startExternalPath("/Users/user/Projects/MyOtherProject")// Give it full path for external directories
        .setExcludePackages(new String[]{"src.main.java.model"}) // Refers to /Users/user/Projects/MyOtherProject/src/main/java/model and skips this directory.
        .build();

 CommentProcessor commentProcessor = new CommentProcessor(commentRemover);
                  commentProcessor.start();        
  }

答案 7 :(得分:0)

如果代码分别处理单行注释和多行注释会更好。有什么建议吗?

    public class RemovingCommentsFromFile {

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

    BufferedReader fin = new BufferedReader(new FileReader("/home/pathtofilewithcomments/File"));
    BufferedWriter fout = new BufferedWriter(new FileWriter("/home/result/File1"));


    boolean multilinecomment = false;
    boolean singlelinecomment = false;


    int len,j;
    String s = null;
    while ((s = fin.readLine()) != null) {

        StringBuilder obj = new StringBuilder(s);

        len = obj.length();

        for (int i = 0; i < len; i++) {
            for (j = i; j < len; j++) {
                if (obj.charAt(j) == '/' && obj.charAt(j + 1) == '*') {
                    j += 2;
                    multilinecomment = true;
                    continue;
                } else if (obj.charAt(j) == '/' && obj.charAt(j + 1) == '/') {
                    singlelinecomment = true;
                    j = len;
                    break;
                } else if (obj.charAt(j) == '*' && obj.charAt(j + 1) == '/') {
                    j += 2;
                    multilinecomment = false;
                    break;
                } else if (multilinecomment == true)
                    continue;
                else
                    break;
            }
            if (j == len)
            {
                singlelinecomment=false;
                break;
            }
            else
                i = j;

            System.out.print((char)obj.charAt(i));
            fout.write((char)obj.charAt(i));
        }
        System.out.println();
        fout.write((char)10);
    }
    fin.close();
    fout.close();

}
相关问题