Removing all types of comments in java file

You can remove all single- or multi-line block comments (but not line comments with //) by searching for the following regular expression in your project(s)/file(s) and replacing by $1:

^([^"\r\n]*?(?:(?<=')"[^"\r\n]*?|(?<!')"[^"\r\n]*?"[^"\r\n]*?)*?)(?<!/)/\*[^\*]*(?:\*+[^/][^\*]*)*?\*+/

It’s possible that you have to execute it more than once.

This regular expression avoids the following pitfalls:

  1. Code between two comments /* Comment 1 */ foo(); /* Comment 2 */

  2. Line comments starting with an asterisk: //***NOTE***

  3. Comment delimiters inside string literals: stringbuilder.append("/*");; also if there is a double quote inside single quotes before the comment

To remove all single-line comments, search for the following regular expression in your project(s)/file(s) and replace by $1:

^([^"\r\n]*?(?:(?<=')"[^"\r\n]*?|(?<!')"[^"\r\n]*?"[^"\r\n]*?)*?)\s*//[^\r\n]*

This regular expression also avoids comment delimiters inside double quotes, but does NOT check for multi-line comments, so /* // */ will be incorrectly removed.

Leave a Comment