删除字符串中的注释 [英] Remove comments in a string
本文介绍了删除字符串中的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private static String filterString(String code) {
String partialFiltered = code.replaceAll("/\\*.*\\*/", "");
String fullFiltered = partialFiltered.replaceAll("//.*(?=\\n)", "");
return fullFiltered;
}
我尝试使用上面的代码删除字符串中的所有注释,但不是工作-请帮忙。
I tried above code to remove all comments in a string but it isn't working - please help.
推荐答案
与 // single
和多行 / *注释* /
。
String sourceCode =
"/*\n"
+ " * Multi-line comment\n"
+ " * Creates a new Object.\n"
+ " */\n"
+ "public Object someFunction() {\n"
+ " // single line comment\n"
+ " Object obj = new Object();\n"
+ " return obj; /* single-line comment */\n"
+ "}";
System.out.println(sourceCode.replaceAll(
"//.*|/\\*((.|\\n)(?!=*/))+\\*/", ""));
输入:
/*
* Multi-line comment
* Creates a new Object.
*/
public Object someFunction() {
// single line comment
Object obj = new Object();
return obj; /* single-line comment */
}
输出:
public Object someFunction() {
Object obj = new Object();
return obj;
}
这篇关于删除字符串中的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文