Pattern regex = Pattern.compile("/\\*[^\\r\\n]*[\\r\\n]+(.*?)[\\r\\n]+[^\\r\\n]*\\*+/", Pattern.DOTALL);
This works because comments can't be nested in Java.
It is important to use a reluctant quantifier (.*?
) or we will match everything from the first comment to the last comment in a file, regardless of whether there is actual code in-between.
/\*
matches /*
[^\r\n]*
matches whatever else is on the rest of this line.
[\r\n]+
matches one or more linefeeds.
.*?
matches as few characters as possible.
[\r\n]+
matches one or more linefeeds.
[^\r\n]*
matches any characters on the line of the closing */
.
\*/
matches */
.