You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java使用Regex校验文本文件每行末尾两位数字是否大于70的实现问题

问题诊断
  • 正则表达式转义错误:Java字符串中表示正则的\d需要双转义为\\d,否则会触发编译错误,原本的正则无法正确识别行格式。
  • 逻辑完全错位:当前代码把「正则是否匹配行格式」和「是否超速」的判断逻辑绑定了,正则仅应该用来校验行格式合法性、捕获末尾两位数值,本身不承载数值大小判断的能力。
  • 缺少数值提取、比较逻辑:没有通过正则捕获组提取末尾两位数字,也没有将其转为整数和70做比较,完全没有实现需求的核心逻辑。
  • 行格式匹配容错不足:没有考虑行尾可能存在空格的情况,示例内容里每行末尾就有空格,会导致原本合法的行匹配失败。
修正后代码
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main {
    private final int LINES_TO_READ = 3;
    // 正则增加捕获组提取末尾两位数字,末尾加\s*匹配可能存在的空白字符
    private final String REGEX = ".{2}\\d{5}-(\\d{2})\\s*";
    private final Pattern PATTERN = Pattern.compile(REGEX);
    private final int SPEED_LIMIT = 70;

    public void testFile(String fileName) {
        int lineCounter = 1;
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { // 用try-with-resources自动关流
            String line = br.readLine();
            while ((line != null) && (lineCounter <= LINES_TO_READ)) {
                Matcher matcher = PATTERN.matcher(line);
                if (matcher.matches()) {
                    // 提取捕获组的两位数字,转为int
                    int speed = Integer.parseInt(matcher.group(1));
                    if (speed > SPEED_LIMIT) {
                        System.out.println("They are speeding.");
                    } else {
                        System.out.println("They are not speeding.");
                    }
                } else {
                    // 格式不匹配的行单独提示,避免和超速逻辑混淆
                    System.out.printf("第%d行格式不符合要求%n", lineCounter);
                }
                line = br.readLine();
                lineCounter++;
            }
        } catch (Exception ex) {
            System.out.println("Exception occurred: " + ex);
        }
    }

    public static void main(String[] args) {
        Main vtf = new Main();
        vtf.testFile("Data.txt");
    }
}
运行效果

针对你提供的测试文本,运行输出结果为:

They are not speeding.
They are not speeding.
They are speeding.

内容的提问来源于stack exchange,提问作者user17223643

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 04:36:04