-4

我想做一个获取字符串的函数,如果它有内联注释,它会删除它。

公共类样本{

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) 处得到空指针异常。这是因为它不接受评论。

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

4

2 回答 2

1

尝试正则表达式

    code = code.replaceAll("/\\*\\*.*?\\*/", "");
于 2013-09-19T06:12:13.210 回答
0

也许这个?

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

  • //.*?($|\n)全部// comment

于 2013-09-19T06:14:42.030 回答