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();
}
### 使用 Selenium 和 浏览器开发者工具 (F12) 选择下拉菜单 为了实现通过 Selenium 操作浏览器并选择特定的下拉菜单项,可以按照如下方式处理: #### 准备工作 确保已安装谷歌浏览器及其对应的驱动包,并且两者版本匹配[^2]。 ```bash pip install selenium ``` #### 导入必要的库 导入 `Select` 类用于操作 `<select>` 标签下的选项[^3]。 ```python from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.select import Select ``` #### 初始化 WebDriver 并打开目标网页 创建 Chrome 浏览器实例,并加载含有 Element UI 组件的目标页面。 ```python driver = webdriver.Chrome(executable_path='/path/to/chromedriver') url = 'https://example.com/page-with-element-ui-dropdown' driver.get(url) # 显式等待直到找到指定的选择框元素变得可见 dropdown_element = WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, '.el-select .el-input__inner')) ) ``` #### 打开开发者工具查看元素路径 利用 F12 开启开发者工具,在 Elements 面板中定位到所需的下拉列表组件。对于某些复杂的前端框架如 Element UI,可能无法直接获取简单的 XPath 表达式来唯一标识该控件;此时可尝试复制完整的 XPath 或者 CSS Selector 来精确定位[^1]。 #### 模拟用户交互行为触发下拉菜单显示 由于部分现代 Web 应用可能会延迟渲染实际的内容节点,因此需要模拟用户的点击动作使隐藏的选项显现出来以便进一步操作。 ```python # 点击输入框激活下拉菜单 dropdown_element.click() # 如果有更多动态加载的数据,则需适当增加延时以允许数据完全呈现 import time time.sleep(1) # 调整此数值取决于具体应用响应速度 ``` #### 定位具体的选项并执行选择 一旦确认了可用的查询表达式能够准确定位到期望的子项目之后,就可以继续编写代码完成最终的选择过程。 ```python option_locator = (By.XPATH, "//li[contains(@class,'el-select-dropdown__item') and contains(text(), 'Option Text')]") try: option_to_select = WebDriverWait(driver, 5).until(EC.element_to_be_clickable(option_locator)) option_to_select.click() except Exception as e: print(f"未能成功选取选项: {e}") finally: driver.quit() # 关闭浏览器窗口 ``` 上述流程展示了如何借助 Selenium 结合浏览器自带的调试功能精确控制 web 页面上的复杂 GUI 控制结构,特别是针对那些由第三方 JavaScript 库构建而成的对象模型提供了有效的解决方案[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值