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
*/
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
*/
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.
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();
}
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
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) «$»
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.
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.
Open Notepad++, press Ctrl + Shift + F
Click Find in files
tab.
Paste the project directory root path into Directory
To remove all block-comments (Credits to user Ahmet Karakaya)
\/\*([\S\s]+?)\*\/
<leave it empty, no empty space>
*.java
(can be *.*
) if want to search in all filesTo remove all single line-comments
\/\/([\S\s]+?)\n
<leave it empty, no empty space>
*.java
(can be *.*
) if want to search in all filesTake 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.
There is a plugin which doest this in a single click. This will Comment / Remove out all System.Out's.
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.
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)
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;
}
}
}
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);
}