How to write a program that reads a Java source file and displays all the comments contained in the file? Can this be done with regular expressions?
- 2“I had one problem and I decided to solve it on a regular basis. Now I have two problems.” - Yuriyi SPb ♦
3 answers
This is not difficult to do with regular expressions. It is enough to consider that the text can meet. Like in Java, there are no longer any affected syntaxes.
"(?:\\.|[^"])+" | (\/\/[^\n]*)(?=\n|$) | (\/\*.*?\*\/) This is a multi-line regular expression that performs the task. Sign of the comment is the presence of text in the first or second preserving group.
This is difficult to do with regular expressions.
You need to parse the entire text of the source code, taking into account the different types of comments, their entries in the lines. Consider nested comments and nested lines.
A simple solution is to find and use a ready-made parser, sure for Java there are many different ones.
- This can be done with regular expressions - ReinRaus
- @ReinRaus agree, corrected the answer - Kromster
In general, comments:
- start with
// - start with
/*and end with*/
In the second case, the comment is usually multi-line.
Also, these characters can appear in strings. And then there are Java-doc comments.
In general, this is not a trivial task.