Domanda

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
È stato utile?

Soluzione 2

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());
    }

Altri suggerimenti

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 */

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top