Adam Siemion
Adam Siemion

Reputation: 16039

Extract Java comment body (without //, /*, */)

I use the eclipse java jdt parser, which seems to be missing the following feature: extracting comment bodies.

The following code:

class CommentBodyExtractor extends ASTVisitor {
  @Override public boolean visit(BlockComment node) {
    final int start = node.getStartPosition();
    final int end = start + node.getLength();
    final String comment = source.substring(start, end);
    System.out.println(comment);
    return false;
  }
}

when run on the following code:

/* 
* comment_body
*/

returns the complete comment code, while what I am looking for is code that will return just comment_body.

I could do simple string manipulation like remove /* from the beginning of the string and */ from the end and * from line beginnings. However I would like to use a more elegant way (some library?), do you know any?

Upvotes: 0

Views: 315

Answers (1)

Stephan Herrmann
Stephan Herrmann

Reputation: 8178

A parser needs well-defined rules in order to process input text. JLS does not define any structure for the text between /* and */, hence a parser cannot do much.

If you want to programmatically operate on comments, you should probably use javadoc comments, from which the JDT parser creates a structured Javadoc element, that reflects the semantic content rather than the raw text.

Upvotes: 1

Related Questions