javaremove-method

How do I remove characters between /* and */ from a string


I am trying to remove characters of comments(/* */) from the String s, but I am not sure how I extract them, especially, from the second comment. This is my code:

public String removeComments(String s)
{
    String result = "";
    int slashFront = s.indexOf("/*");
    int slashBack = s.indexOf("*/");
    
    if (slashFront < 0) // if the string has no comment
    {
        return s;
    }
    // extract comment
    String comment = s.substring(slashFront, slashBack + 2);
    result = s.replace(comment, "");
    return result;
    }

In tester class:

System.out.println("The hippo is native to Western Africa. = " + tester.removeComments("The /*pygmy */hippo is/* a reclusive*/ /*and *//*nocturnal animal */native to Western Africa."));

output: The hippo is/* a reclusive*/ /*and *//*nocturnal animal */native to Western Africa. // expected: The hippo is native to Western Africa.

As you can see, I can not remove comments but the first one.


Solution

  • It’s a one-liner:

    public String removeComments(String s) {
        return s.replaceAll("/\\*.*?\\*/", "");
    }
    

    This caters for any number of comments, including zero.