Close

Find comments in Source Code Using Java Regex

[Last Updated: Feb 6, 2017]

Java Regex 

This regex pattern can be used to find Java source code comments that start with /* and end with */

Pattern

(?s)/\*(.)*?\*/
(?s)DOTALL flag to treat line terminators (\n or \r) as literals
/\*Start of comment literal, escaping *
(.)*Any character zero or more times.
?The reluctant quantifier, finds matches in smaller parts
\*/End of comment literal, escaping *


Example

Java source file we want to search for the comments:

/**
* Test java source.
*/
public class TestSource {

/**
* doSomething
*
* @param arg
*/
public void doSomething (Object arg) {
}

/**
* @param args
*/
public static void main (String[] args) {
}
}


Using Regex:

public static void main (String[] args) throws Exception {
String source = getJavaSource();
Pattern pattern = Pattern.compile("(?s)/\\*(.)*?\\*/");
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
System.out.println(matcher.group());
}
}


Output:

/**
* Test java source.
*/
/**
* doSomething
*
* @param arg
*/
/**
* @param args
*/

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.0.4

java-comments-regex Select All Download
  • java-comments-regex
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • CommentRegexTest.java
          • resources

    See Also