Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing the comments from a string

Tags:

java

I'd like to do a function which gets a string and in case it has inline comments it removes it.

public class sample {

    public static void main(String[] args) {
        String code = "/**THIS IS SAMPLE CODE */ public class TestFormatter{public static void main(String[] args){int i =2; String s= \"name\";\\u give give change the values System.out.println(\"Hello World\");//sample}}";

        CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(null);

        TextEdit textEdit = codeFormatter.format(
                CodeFormatter.K_COMPILATION_UNIT, code1, 0, code1.length(), 0,
                null);
        IDocument doc = new Document(code1);
        try {
            textEdit.apply(doc);
            System.out.println(doc.get());
        } catch (MalformedTreeException e) {
            e.printStackTrace();
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }
}

I am getting null pointer exception at textEdit.apply(doc). This is because it is not accepting the comments.

Can you tell me what's the best way to remove the comments from the string? (please don't advice too advanced solutions).

like image 799
sam Avatar asked Jul 26 '26 20:07

sam


1 Answers

replaceAll("((/\\*)[^/]+(\\*/))|(//.*)", "")

This will remove single line, multi-line or doc comments.

The JavaScript compatible regex is ((/\*)[^/]+(\*/))|(//.*), which you can try with regexpal.com.