从字符串中删除注释

3
我希望做一个函数,它可以获取一个字符串,并在其中包含内联注释时将其移除。
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();
        }
    }
}

我在textEdit.apply(doc)处遇到了空指针异常。这是因为它不接受注释。

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


@sᴜʀᴇsʜᴀᴛᴛᴀ 这怎么可能是重复的呢?那个是关于XML注释的。这个是关于Java内联注释的。而且还使用了不同的库。 - Rohit Jain
“我想写一个函数,它可以获取一个字符串,并在该字符串包含内联注释时将其删除。” 为什么要这样做? - NullUserException
3
如果您使用任何第三方库,请明确说明并提供API链接。 - Rohit Jain
@RohitJain 我也认为这个正则表达式是多余的。已删除。 - Suresh Atta
这个答案看起来很有帮助:http://stackoverflow.com/questions/5433449/regex-to-remove-java-comments-block-containing-specific-words 或者这个: https://dev59.com/-2LVa4cB1Zd3GeqP0eDr - Ernestas Kardzys
我怀疑正则表达式不是这项工作的正确工具。我会使用Java扫描器,例如随JavaCC一起提供的扫描器。 - user207421
2个回答

1

尝试

replaceAll("(?s)/\\*.*?\\*/", "")

例子:

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}}";
System.out.println(code.replaceAll("(?s)/\\*.*?\\*/", ""));

输出:

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}}

PS.注意:

如果您也想删除最后的注释//sample}}

那么请使用split()函数。

System.out.println(code.replaceAll("(?s)/\\*.*?\\*/", "").split("//")[0]);
// keep in Mind it will also Remove  }} from //sample}} 

输出:

 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");

我不是downvoter,但如果像*..*\或\这样的注释被放置在字符串中,你的正则表达式会出问题。在这种情况下,它们不是注释,而是简单的字面量,不应该被删除。解析代码并不那么容易,也可能不应该使用正则表达式来完成... - Pshemo
1
@Tarsem:正则表达式看起来和我的答案一样。在复制答案时,请至少提到原始作者。顺便说一句,我没有投反对票。 - user235273
2
@kadaj那么为什么这个问题43分钟前就有答案了,而你的是24分钟前回答的——还是来自另一个答案? - MadProgrammer
@MadProgrammer:看一下修改记录。不管怎样,没什么大不了的。我的答案是通过自己在regexpal.com上实验得出的。 - user235273

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

这将删除单行、多行或文档注释。
JavaScript兼容的正则表达式为((/\*)[^/]+(\*/))|(//.*),您可以在regexpal.com上尝试。

空指针异常,实际上问题不在replaceAll方法。我在textedit.apply()处遇到了空指针异常。如果字符串顺序不正确,则代码将无法格式化为Java。 - sam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接