为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Qyouu 2023-03-09 16:50:49
我想从 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。
查看完整描述

4 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

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


以下正则表达式将执行此操作,用作$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


查看完整回答
反对 回复 2023-03-09
?
紫衣仙女

TA贡献1839条经验 获得超15个赞

我推荐一个两步过程;一个基于行尾 (//),另一个不基于行尾 (/* */)。

我喜欢帕维尔的想法;但是,我看不到它如何检查以确保星号是斜线后的下一个字符,反之亦然。

我喜欢安德烈亚斯的想法;但是,我无法让它处理多行注释。

https://docs.oracle.com/javase/specs/jls/se12/html/jls-3.html#jls-CommentTail


查看完整回答
反对 回复 2023-03-09
?
守着一只汪

TA贡献1872条经验 获得超3个赞

正如其他人所说,正则表达式在这里不是一个好的选择。您可以使用简单的DFA来完成此任务。

这是一个示例,它将为您提供多行注释 ( /* */) 的间隔。

您可以对单行注释 ( // -- \n) 执行相同的方法。


    String input = ...; //here's your input String


    //0 - source code, 

    //1 - multiple lines comment (start) (/ char)

    //2 - multiple lines comment (start) (* char)

    //3 - multiple lines comment (finish) (* char)

    //4 - multiple lines comment (finish) (/ char)

    byte state = 0; 

    int startPos = -1;

    int endPos = -1;

    for (int i = 0; i < input.length(); i++) {

        switch (state) {

        case 0:

            if (input.charAt(i) == '/') {

                   state = 1;

                   startPos = i;

            }

            break;

        case 1:

            if (input.charAt(i) == '*') {

                state = 2;

            }

            break;

        case 2:

            if (input.charAt(i) == '*') {

               state = 3;

            }

            break;

        case 3:

            if (input.charAt(i) == '/') {

                state = 0;

                endPos = i+1;


                //here you have the comment between startPos and endPos indices,

                //you can do whatever you want with it

            }


            break;

        default:

            break;

        }

    }


查看完整回答
反对 回复 2023-03-09
?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

也许,最好从多个简单的表达式开始,逐步进行,例如:

.*(\s*\/\*.*|\s*\/\/.*)

最初删除内联评论。

演示

测试

import java.util.regex.Matcher;

import java.util.regex.Pattern;


final String regex = "(.*)(\\s*\\/\\*.*|\\s*\\/\\/.*)";

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


final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);

final Matcher matcher = pattern.matcher(string);


// The substituted value will be contained in the result variable

final String result = matcher.replaceAll(subst);


System.out.println("Substitution result: " + result);


查看完整回答
反对 回复 2023-03-09
  • 4 回答
  • 0 关注
  • 183 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信