gpt4 book ai didi

java - 从java中的源代码中删除注释

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:30:42 26 4
gpt4 key购买 nike

我想从 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。

最佳答案

要使其工作,您需要“跳过”字符串文字。您可以通过匹配字符串文字、捕获它们以便保留它们来做到这一点。

以下正则表达式将执行此操作,使用 $1作为替换字符串:

//.*|/\*(?s:.*?)\*/|("(?:(?<!\\)(?:\\\\)*\\"|[^\r\n"])*")

参见 regex101用于演示。

然后是 Java 代码:

str1.replaceAll("//.*|/\\*(?s:.*?)\\*/|(\"(?:(?<!\\\\)(?:\\\\\\\\)*\\\\\"|[^\r\n\"])*\")", "$1")

解释

//.*                      Match // and rest of line
| or
/\*(?s:.*?)\*/ Match /* and */, with any characters in-between, incl. linebreaks
| or
(" Start capture group and match "
(?: Start repeating group:
(?<!\\)(?:\\\\)*\\" Match escaped " optionally prefixed by escaped \'s
| or
[^\r\n"] Match any character except " and linebreak
)* End of repeating group
") Match terminating ", and end of capture group
$1                        Keep captured string literal

关于java - 从java中的源代码中删除注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56906528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com