Reputation: 63
I want to know the what will be the regular expression of the below scenario?
I want to find out the multi-line comments from my java code as below.
Text 1::
/*
This is my multi-line comment.
This is second line of the comment.
*/
But I do not want to find out the expression which is as below.
Text 2::
/**
Any method description.
*/
So, I just want to extract the comments which will be like Text 1 but not like Text 2.
I have tried this regex:
/*([^*]|[\r\n]|(*+([^*/]|[\r\n])))**+/
Can anyone help me with this?
Thanks
Upvotes: 2
Views: 90
Reputation: 30991
When using e.g. online regex tools, when the whole regex is enclosed in slashes, the regex required in your case is:
\/\*(?!\*).+?\*\/
Details:
\/
- A slash (quoted).\*
- An asterrisk (also quoted).(?!\*)
- Negative lookahead for an asterrisk (quoted)..+?
- A non-empty sequence of any chars, reluctant version.
Due to DOTALL option, this sequence includes also newline chars.\*\/
- An asterrisk and a slash (both quoted).But in Java context:
So the regex to be included in Java code should be rewritten to:
/\\*(?!\\*).+?\\*/
Below you have an example Java code, processing your source text:
import java.util.*;
import java.lang.*;
import java.util.regex.*;
class Rextester {
public static void main(String args[]) {
String src = "/*\n" +
"This is my multi-line comment.\n" +
"This is second line of the comment.\n" +
"*/\n" +
"/**\n" +
"Any method description.\n" +
"*/";
Matcher m = Pattern.compile("/\\*(?!\\*).+?\\*/", Pattern.DOTALL).matcher(src);
int cnt = 0;
while (m.find()) {
System.out.println(String.format("Found %d:\n%s", ++cnt, m.group()));
}
}
}
It prints:
Found 1:
/*
This is my multi-line comment.
This is second line of the comment.
*/
As you can see, just the first comment, omitting the second.
As an excercise, change "/**\n"
in the above code to "/* *\n"
(add
a space between asterrisks).
Then run your code and you will see that this time both comments
were printed, because the negative lookahead checks for an asterrisk
immediately following the first one.
Upvotes: 2