31

I have many comments like following. Is there simple way to remove all comments?

IDE Eclipse Kepler

/* 34:   */

/*

 * JD-Core Version:    0.7.0.1

 */
Ahmet Karakaya
  • 9,899
  • 23
  • 86
  • 141

12 Answers12

71

I have found the solution Regular Expression with multiple lines search.

Here are the regular expression used to find two types of comments

\/\*([\S\s]+?)\*\/ and (?s)/\*.*?\*/

Open the .java file with comments and open the Search dialog.(Search -> File Search) and paste one of the above reg-ex and check the Regular expression tick box on the right side. Now you can search and select "Replace All" to replace it with nothing typed in the second box.

Using replace-with option I have cleaned all comments from java files.

Community
  • 1
  • 1
Ahmet Karakaya
  • 9,899
  • 23
  • 86
  • 141
7

I made a open source library for this purpose, you can remove Java Comments.

It supports remove or NOT remove TODO's.

Also it supports JavaScript , HTML , CSS , Properties , JSP and XML Comments too.

Little code snippet how to use it:

 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();        
  }
Ertuğrul Çetin
  • 5,131
  • 5
  • 37
  • 76
6

I've done this with the Ctrl+F command and this regex.

This only replace //comments

//(.?+)+

enter image description here

Wesos de Queso
  • 1,526
  • 1
  • 21
  • 23
4

Since nobody mentioned text processing tools grep, sed, awk, etc. in *NIX, I post my solution here.

If your os is *NIX, you can use the text processing tool sed to remove the comments.

sed '/\/\*/{:loop;/\/\*.*\*\//{d;b out};N;b loop};:out' yourfile.java
alijandro
  • 11,627
  • 2
  • 58
  • 74
  • 1
    The question specifically states how to do it in Eclipse, but if someone reaches this Q&A looking for **any** way of removing comments, your answer will be useful, so disregarding applicability in answering the Q above, +1 – Mindwin Remember Monica Apr 06 '16 at 14:09
  • 2
    I get `sed: 1: "/\/\*/{:loop;/\/\*.*\*\ ...": unexpected EOF (pending }'s)` when I run it. – Michael Ressler Jul 05 '18 at 21:51
2

This one is working well for me... I added it as an IntelliJ IDEA search template for JavaDoc and/or single line comments..

(?sm)(^(?:\s*)?((?:/\*(?:\*)?).*?(?<=\*/))|(?://).*?(?<=$))

Definition


    Options: ^ and $ match at line breaks

    Match the remainder of the regex with the options: dot matches newline (s); ^ and $ match at line breaks (m) «(?sm)»
    Match the regular expression below and capture its match into backreference number 1 «(^(?:\s*)?((?:/\*(?:\*)?).*?(?<=\*/))|(?://).*?(?<=$))»
       Match either the regular expression below (attempting the next alternative only if this one fails) «^(?:\s*)?((?:/\*(?:\*)?).*?(?<=\*/))»
          Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
          Match the regular expression below «(?:\s*)?»
             Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
             Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.) «\s*»
                Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
          Match the regular expression below and capture its match into backreference number 2 «((?:/\*(?:\*)?).*?(?<=\*/))»
             Match the regular expression below «(?:/\*(?:\*)?)»
                Match the character “/” literally «/»
                Match the character “*” literally «\*»
                Match the regular expression below «(?:\*)?»
                   Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
                   Match the character “*” literally «\*»
             Match any single character «.*?»
                Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
             Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=\*/)»
                Match the character “*” literally «\*»
                Match the character “/” literally «/»
       Or match regular expression number 2 below (the entire group fails if this one fails to match) «(?://).*?(?<=$)»
          Match the regular expression below «(?://)»
             Match the characters “//” literally «//»
          Match any single character «.*?»
             Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
          Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=$)»
             Assert position at the end of a line (at the end of the string or before a line break character) «$»
Edward J Beckett
  • 5,061
  • 1
  • 41
  • 41
1

I think eclipse supports regex search and replace. I'd try something like:

search: (?s)(?>\/\*(?>(?:(?>[^*]+)|\*(?!\/))*)\*\/)
replace all with no-space-character or nothing literally

also related to the topic: Eclipse, regular expression search and replace

I edited the regex and tested it: http://regex101.com/r/sU4vI2 Not sure if it works in your case.

Community
  • 1
  • 1
TheWhiteLlama
  • 1,276
  • 1
  • 18
  • 31
1

I have many comments like following. Is there simple way to remove all comments?

For me I used Notepad++ and it was able to replace all files in my project all in one go.

  1. Open Notepad++, press Ctrl + Shift + F

  2. Click Find in files tab.

  3. Paste the project directory root path into Directory

  4. To remove all block-comments (Credits to user Ahmet Karakaya)

    • Find what:\/\*([\S\s]+?)\*\/
    • Replace with: <leave it empty, no empty space>
    • Filters: *.java (can be *.*) if want to search in all files
    • Click Find All to ensure the search results is what you intended to replace.
    • Click Replace in Files
  5. To remove all single line-comments

    • Find what:\/\/([\S\s]+?)\n
    • Replace with: <leave it empty, no empty space>
    • Filters: *.java (can be *.*) if want to search in all files
    • Click Find All to ensure the search results is what you intended to replace.
    • Click Replace in Files

Take Note: Step 5 will remove all lines which begin with // till the next newline character. If you have URLs in your code, it will remove it as well. If you do not want to write another REGEX, you can always replace https:// to something like https:ZZ first and then replace it back to the original state after you removed all single line comments.

user3437460
  • 17,253
  • 15
  • 58
  • 106
0

There is a plugin which doest this in a single click. This will Comment / Remove out all System.Out's.

Refer this, this and this.

Chandrayya G K
  • 8,719
  • 5
  • 40
  • 68
  • 3
    If all you're going to do is refer OP elsewhere, it's better to post your links in a comment. Answers should be able to stand on their own, regardless of whether a link is present or not. – awksp Jun 20 '14 at 10:50
  • 404 , 404 , ehm – GOXR3PLUS Dec 18 '18 at 15:03
0

Eclipse has several shortcuts for commenting/uncommenting code.

For single line java code comment : Ctrl + / (Forwards Slash) and

Single line uncomment : Ctrl + \ (Backslash)

For multiple line java code comment : Ctrl + Shift + / (Forwards Slash) and

Multiline uncomment : Ctrl + Shift + \ (Backslash)

Note: For multiline comments, select all the lines that you wish to comment/uncomment first.

Also Ctrl + Shift + L will open a list of all major shortcuts for Eclipse.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Yasin
  • 1,906
  • 1
  • 21
  • 37
  • so how I can replace all comments between /**/ and after // – Ahmet Karakaya Jun 20 '14 at 11:04
  • 1
    For single line comments just take the cursor to that line (or if there are multiple lines having comments starting with // then select all the lines) and press Ctrl + \ (Backslash), if this does not work try Ctrl + / (Forwardslash). It depends on your version. Same is the case with multiline comments. Select all the lines and press Ctrl + Shift + \ (Backslash) (or / (Forwards Slash)). – Yasin Jun 20 '14 at 12:51
  • I think you are missing something important. I have 10K files, Do not you want to make them all manually ? :) – Ahmet Karakaya Jun 20 '14 at 12:53
  • Then you will have to write a small program that does the job. – Yasin Jun 23 '14 at 10:52
  • you are gettın far away from the question. Anyway I have found the solution. Thanks – Ahmet Karakaya Jun 23 '14 at 11:04
0

You might try using uncrustify (http://uncrustify.sourceforge.net/) to reformat your /* block comments */ to // double-slash comments

That would make your regex a bit "safer" -- just look for \*s// lines and delete them (easy sed operation)

Shaun
  • 3,777
  • 4
  • 25
  • 46
0

here's my solution:

new FileGenerator().start(new File("C:\\yourFolder"), e->{
            String str = ReadFileToString.read(e);
            Comments co = null;
            try {
                co = new Comments(str);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            e.delete();
            PrintStream stream = new PrintStream(e.getAbsolutePath());
            stream.println(co.analysis());
            stream.close();
        });
public class FileGenerator {

    /*
    *  new FileGenerator().start(new File("C:\\folders"), e->{
            String str = ReadFileToString.read(e);
            e.delete();
            PrintStream stream = new PrintStream(e.getAbsolutePath());
            stream.println(CommentRemover.init(str));
            stream.close();
        });
    * */

    public interface callback{
        void cb(File f) throws IOException;
    }

    public void start(File f, callback cb) throws IOException {
        if (f.isDirectory()) {
            File[] arr = f.listFiles();
            for (File tmp : arr) {
                if (tmp.isDirectory())
                    start(tmp,cb);
                else
                    cb.cb(tmp);
            }
        }
    }
}
package xyz.laremehpe.comment;

public class Comments {
    StringBuilder template;
    final String holder1 = "←";
    final String holder2 = "↓";
    final String holder3 = "↖";
    int quota = 1024;

    public Comments(String template) throws Exception {
        this.template = new StringBuilder(template);
        //for safety
        if (template.indexOf(holder1) > -1)
            throw new Exception("this file already have the placeholder1, please check your file before compile!!");
        if (template.indexOf(holder2) > -1)
            throw new Exception("this file already have the placeholder2, please check your file before compile!!");
        if (template.indexOf(holder3) > -1)
            throw new Exception("this file already have the placeholder3, please check your file before compile!!");
        //for safety
    }

    public StringBuilder analysis() {
        int index3,index2,index1;
        String[] str1 = new String[quota];
        index1 = escape(template,"\\",holder1,str1);
//----------------------------------------------------------------------------
        String[] str2 = new String[quota];
        index2 = replace(template,"\"",holder2,str2);
//----------------------------------------------------------------------------
        String[] str3 = new String[quota];
        index3 = replace(template,"\'",holder3,str3);
//----------------------------------------------------------------------------
        replaceA(template,"//","\n");
        replaceB(template,"/*","*/");
//----------------------------------------------------------------------------
        restore(template,str3,index3,holder3);
        restore(template,str2,index2,holder2);
        restore(template,str1,index1,holder1);

        return template;
    }

    private void restore(StringBuilder sb,String[] from,int i,String holder){
        for (;i > -1; i--) {
            String ch = holder+i;
            int po = sb.indexOf(ch);
            if(po > -1)
            sb.replace(po,po+ch.length(),from[i]);
        }
    }

    private int escape(StringBuilder sb,String ch,String holder,String[] restore){
        int po1 = sb.indexOf(ch);
        int po2 = po1+2;

        int index = 0;
        while(po1 != -1){
            restore[index] = sb.substring(po1, po2);
            sb.replace(po1,po2,holder+index);
            index++;
            po1 = sb.indexOf(ch);
            po2 = po1+2;
        }
        return index;
    }

    private int replace(StringBuilder sb,String ch,String holder,String[] restore){
        int po1 = sb.indexOf(ch);
        int po2 = sb.indexOf(ch,po1+1)+1;

        int index = 0;
        while(po1 != -1 && po2 != -1){
            restore[index] = sb.substring(po1, po2);
            sb.replace(po1,po2,holder+index);
            index++;
            po1 = sb.indexOf(ch);
            po2 = sb.indexOf(ch,po1+1)+1;
        }
        return index;
    }

    private void replaceA(StringBuilder sb,String from,String to){
        int po1 = sb.indexOf(from);
        int po2 = sb.indexOf(to,po1+1);

        while(po1 != -1 && po2 != -1){
            sb.replace(po1,po2,"");
            po1 = sb.indexOf(from);
            po2 = sb.indexOf(to,po1+1);
        }
    }

    private void replaceB(StringBuilder sb,String from,String to){
        int po1 = sb.indexOf(from);
        int po2 = sb.indexOf(to,po1+1)+2;

        while(po1 != -1 && po2 != -1){
            sb.replace(po1,po2,"");
            po1 = sb.indexOf(from);
            po2 = sb.indexOf(to,po1+1)+2;
        }
    }
}
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 03 '22 at 07:56
0

I write this code to delete comment from my java file.

Take a look, if it's helpful.

    public static void main(String[] args) throws IOException {
    final var lines = Files.readAllLines(Path.of("myfile.txt"));

    var result = new ArrayList<String>();
    boolean blockComment = false;

    for (final String line : lines) {
        if (line.contains("//")) {
            var index = line.indexOf("//");
            if (index == 0) {
                // do nothing.
            } else {
                final var newline = line.substring(0, index);
                result.add(newline);
            }
        } else {
            if (line.contains("/*")) {
                blockComment = true;
                var firstIndex = line.indexOf("/*");
                if (line.contains("*/")) {
                    var lastIndex = line.indexOf("*/");
                    var newline = line.substring(0, firstIndex) + line.substring(lastIndex + 2);
                    result.add(newline);
                    blockComment = false;
                }
            } else if (!line.contains("*/") && blockComment) {
                //do nothing .
            } else if (line.contains("*/") && blockComment) {
                    var lastIndex = line.indexOf("*/");
                    var newline = line.substring(lastIndex + 2);
                    result.add(newline);
                    blockComment = false;
            } else {
                result.add(line);
            }
        }
    }
    final var outputContents = String.join("\n", result);
    Files.writeString(Path.of("output.txt"), outputContents);

    
}
İsmail Y.
  • 3,579
  • 5
  • 21
  • 29