java去除注释

  • 将形如/**/已经//的注释都去掉,代码如下:
  • 这是别人写的,只是拿过来参考下
package removeNotes;

/**
 * Created by 12083 on 2016/9/7.
 */
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class RemoveNotes {
    public static void main(String[] args) {
        String test = ReadFileToString("E:/main.java");
        System.out.println(removeCommentsWithQuoteAndDoubleEscape(test));
    }
    /**
     * 处理双引号和双斜杠注释
     */
    public static String removeCommentsWithQuoteAndDoubleEscape(String code) {
        StringBuilder sb = new StringBuilder();
        int cnt = 0;
        boolean quoteFlag = false;
        for (int i = 0; i < code.length(); i++) {
            //如果没有开始双引号范围
            if (!quoteFlag) {
                //如果发现双引号开始
                if (code.charAt(i) == '\"') {
                    sb.append(code.charAt(i));
                    quoteFlag = true;
                    continue;
                }
                //处理双斜杠注释
                else if (i + 1 < code.length() && code.charAt(i) == '/' && code.charAt(i + 1) == '/') {
                    while (code.charAt(i) != '\n') {
                        i++;
                    }
                    continue;
                }
                //不在双引号范围内
                else {
                    //处理/**/注释段
                    if (cnt == 0) {
                        if (i + 1 < code.length() && code.charAt(i) == '/' && code.charAt(i + 1) == '*') {
                            cnt++;
                            i++;
                            continue;
                        }
                    } else {
                        //发现"*/"结尾
                        if (i + 1 < code.length() && code.charAt(i) == '*' && code.charAt(i + 1) == '/') {
                            cnt--;
                            i++;
                            continue;
                        }
                        //发现"/*"嵌套
                        if (i + 1 < code.length() && code.charAt(i) == '/' && code.charAt(i + 1) == '*') {
                            cnt++;
                            i++;
                            continue;
                        }
                    }
                    //如果没有发现/**/注释段或者已经处理完了嵌套的/**/注释段
                    if (cnt == 0) {
                        sb.append(code.charAt(i));
                        continue;
                    }
                }
            }
            //处理双引号注释段
            else {
                //如果发现双引号结束(非转义形式的双引号)
                if (code.charAt(i) == '\"' && code.charAt(i - 1) != '\\') {
                    sb.append(code.charAt(i));
                    quoteFlag = false;
                }
                //双引号开始了但是还没有结束
                else {
                    sb.append(code.charAt(i));
                }
            }
        }
        return sb.toString();
    }

    /**
     * 从一个文件读入到String
     *
     * @param FilePath
     * @return
     */
    public static String ReadFileToString(String FilePath) {
        FileInputStream fis = null;
        BufferedReader br = null;
        try {
            fis = new FileInputStream(FilePath);
            br = new BufferedReader(new InputStreamReader(fis, "utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //构建成String
        StringBuffer sb = new StringBuffer();
        String temp = null;
        try {
            while ((temp = br.readLine()) != null) {
                sb.append(temp + '\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}
  • 下面重新写了一个简单一点 的:
String removeComments(String curr) {
    StringBuilder builder = new StringBuilder();
    boolean isQuote = false;
    for (int i = 0; i < curr.length(); ++i) {
        if (!isQuote) {
            //now meet the close quote
            if (curr.charAt(i) == '/' && i + 1 < curr.length() && curr.charAt(i + 1) == '/') {
                while (i < curr.length() && curr.charAt(i) != '\n')
                    i++;
                continue;
            } else if (curr.charAt(i) == '/' && i + 1 < curr.length() && curr.charAt(i + 1) == '*') {
                i += 2;
                while (i < curr.length() && curr.charAt(i) != '*' && i + 1 < curr.length() && curr.charAt(i + 1) != '/')
                    i++;
                i++;
                continue;
            } else if (curr.charAt(i) == '"') {
                builder.append(curr.charAt(i));
                isQuote = true;
                continue;
            }
            builder.append(curr.charAt(i));
        } else {
            while (i < curr.length() && curr.charAt(i) != '"')
                builder.append(curr.charAt(i++));
            builder.append('"');
            isQuote = false;
        }
    }
    return builder.toString();
}
  • 测试用例如下:
public static void main(String[] args) {
    print p = new print();
    String s = "int candy(int[] arr) { " +
            "int[] candy = new int[arr.length]; " +
            "for (int i = 0; i < candy.length; ++i)" +
            "    candy[i] = 1;" +
            "for (int i = 1; i < arr.length; ++i) { " +
            "    if (arr[i] > arr[i - 1]) " +
            "      candy[i] = candy[i - 1] + 1; " +
            "}" +
            "for (int i = candy.length - 2; i >= 0; --i) {" +
            "if (arr[i] > arr[i + 1])" +
            "candy[i] = Math.max(candy[i - 1], candy[i + 1]);" +
            "}" +
            "int total = 0;" +
            "for (int i = 0; i < candy.length; ++i)" +
            "total += candy[i];" + "String s = \"/*wangcheng*/\";" +
            "return total;" +
            "}";

    String str = p.removeComments(s);
    System.out.println(str);

    System.out.println();
}
  • 读文件
public String readFile(String fileName) throws FileNotFoundException {
    File file = new File(fileName);
    if (!file.exists()) {
        throw new FileNotFoundException("The file " + fileName + " not found!");
    }
    BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    StringBuilder sb = new StringBuilder();
    String tmp;
    try {
        while ((tmp = bf.readLine()) != null) {
            sb.append(tmp);
            sb.append("\n");
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return sb.toString();
}
要使用Python去除Java文件中的注释,可以使用正则表达式和字符串处理的方法。 首先,我们可以使用正则表达式来匹配Java注释的模式。Java注释有两种形式:行注释(以双斜线“//”开始)和块注释(以“/*”开始,以“*/”结束)。我们可以使用正则表达式“//.*|/\*.*?\*/”来匹配注释的模式。 接下来,我们需要读取Java文件的内容,并使用正则表达式匹配注释的模式,并将匹配到的注释替换为空字符串。可以使用Python的re模块来实现正则表达式操作。 下面是一个简单的Python代码示例,演示了如何去除Java文件中的注释: ```python import re def remove_comments(file_path): # 读取Java文件内容 with open(file_path, 'r') as file: content = file.read() # 使用正则表达式匹配注释模式并替换为空字符串 content = re.sub(r'//.*|/\*.*?\*/', '', content, flags=re.S) # 将处理后的内容写回Java文件 with open(file_path, 'w') as file: file.write(content) # 调用示例 java_file_path = 'example.java' remove_comments(java_file_path) ``` 以上代码中,我们定义了一个`remove_comments`函数,接受Java文件的路径作为参数。函数内部使用`open`函数读取文件内容,并使用`re.sub`函数替换匹配的注释模式为空字符串。最后,将处理后的内容写回Java文件。 注意:这只是一个简单的实现示例,不能处理所有可能的情况。对于复杂的注释模式或特殊情况,可能需要进一步优化或修改正则表达式。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值