1

I want to check if my line contains /* or not. I know how to check if the block comment is in the start:

/* comment starts from the beginning and ends at the end */

if(line.startsWith("/*") && line.endsWith("*/")){

      System.out.println("comment : "+line);  
}

What I want to know is how to figure the comment is, like this:

something here /* comment*/

or

something here /*comment */ something here
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
gecco
  • 281
  • 4
  • 18

3 Answers3

2

This works for both // single and multi-line /* comments */.

Pattern pattern = Pattern.compile("//.*|/\\*((.|\\n)(?!=*/))+\\*/");
String code = " new SomeCode(); // comment \n" + " " + "/* multi\n"
        + " line \n" + " comment */\n"
        + "void function someFunction() { /* some code */ }";
Matcher matcher = pattern.matcher(code);
while (matcher.find()) {
    System.out.println(matcher.group());
}

Output:

// comment 
/* multi
 line 
 comment */
/* some code */
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
1

Try using this pattern :

String data = "this is amazing /* comment */ more data ";
    Pattern pattern = Pattern.compile("/\\*.*?\\*/");

    Matcher matcher = pattern.matcher(data);
    while (matcher.find()) {
        // Indicates match is found. Do further processing
        System.out.println(matcher.group());
    }
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
0

You can to this multiple ways, here is one:

Find the "/*" in your String:

int begin = yourstring.indexOf("/*");

do the same for "*/"

This will get you two Integers with which you can get the substring containing the comment:

String comment = yourstring.substring(begin, end);
Delpes
  • 1,050
  • 7
  • 13