我想从 java 源代码文件中删除所有类型的注释语句。例子:
String str1 = "SUM 10" /*This is a Comments */ ;
String str2 = "SUM 10"; //This is a Comments"
String str3 = "http://google.com"; /*This is a Comments*/
String str4 = "('file:///xghsghsh.html/')"; //Comments
String str5 = "{\"temperature\": {\"type\"}}"; //comments
预期输出:
String str1 = "SUM 10";
String str2 = "SUM 10";
String str3 = "http://google.com";
String str4 = "('file:///xghsghsh.html/')";
String str5 = "{\"temperature\": {\"type\"}}";
我正在使用下面的正则表达式来实现:
System.out.println(str1.replaceAll("[^:]//.*|/\\\\*((?!=*/)(?s:.))+\\\\*/", ""));
这给了我 str4 和 str5 的错误结果。请帮我解决这个问题。
使用 Andreas 解决方案:
final String regex = "//.*|/\\*(?s:.*?)\\*/|(\"(?:(?<!\\\\)(?:\\\\\\\\)*\\\\\"|[^\\r\\n\"])*\")";
final String string = " String str1 = \"SUM 10\" /*This is a Comments */ ; \n"
+ " String str2 = \"SUM 10\"; //This is a Comments\" \n"
+ " String str3 = \"http://google.com\"; /*This is a Comments*/\n"
+ " String str4 = \"('file:///xghsghsh.html/')\"; //Comments\n"
+ " String str5 = \"{\"temperature\": {\"type\"}}"; //comments";
final String subst = "$1";
// The substituted value will be contained in the result variable
final String result = string.replaceAll(regex,subst);
System.out.println("Substitution result: " + result);
它的工作除了 str5。
交互式爱情
紫衣仙女
守着一只汪
宝慕林4294392
相关分类