在java中删除字符串中的注释

在java中删除字符串中的注释,java,Java,我想做一个函数,它得到一个字符串,如果它有内联注释,它会删除它 公共类样本{ 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 value

我想做一个函数,它得到一个字符串,如果它有内联注释,它会删除它

公共类样本{

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, code, 0, code.length(), 0,
            null);
    IDocument doc = new Document(code);
    try {
        textEdit.apply(doc);
        System.out.println(doc.get());
    } catch (MalformedTreeException e) {
        e.printStackTrace();
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}
}我在textEdit.apply(doc)处收到空指针异常。这是因为它不接受评论

您能告诉我从字符串中删除注释的最佳方法是什么吗?(请不要建议太高级的解决方案)。

试试正则表达式

    code = code.replaceAll("/\\*\\*.*?\\*/", "");
也许是这个

code.replaceAll("(/\\*.*?\\*/)|(//.*?($|\n))", "");
  • /\\*.*?\\*/
    删除所有
    /*注释*/

  • /.*($\n)
    all
    //注释


您的问题的答案有什么问题?我打赌NPE是因为textEdit为空。是的,textEdit为空,这就是我获得NPE的原因。我必须删除注释,然后只有文本编辑才会有值。字符串的顺序应该正确,以便将其格式化为java代码。很抱歉,它不起作用