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

如何用Java提取带方括号子串中指定键的值并校验非负

Java提取并校验日志指定字段值的实现方案

实现步骤

  • 从目标子串中提取start和material requests对应的数值
  • 将提取的字符串转为数值类型,校验其是否≥0

具体代码实现

方案1:正则表达式匹配(推荐,适配格式小变动)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogFieldParser {
    public static void main(String[] args) {
        String targetStr = "[start:0 ms, material requests:0 ms, fulfilled requests:329 ms, sum responses:1 ms, total:330 ms]";
        
        // 提取start的数值
        Pattern startPattern = Pattern.compile("start:(\\d+) ms");
        Matcher startMatcher = startPattern.matcher(targetStr);
        int startVal = -1;
        if (startMatcher.find()) {
            startVal = Integer.parseInt(startMatcher.group(1));
        }
        
        // 提取material requests的数值
        Pattern materialPattern = Pattern.compile("material requests:(\\d+) ms");
        Matcher materialMatcher = materialPattern.matcher(targetStr);
        int materialVal = -1;
        if (materialMatcher.find()) {
            materialVal = Integer.parseInt(materialMatcher.group(1));
        }
        
        // 数值校验
        boolean isValid = startVal >= 0 && materialVal >= 0;
        if (isValid) {
            System.out.printf("start值:%d,校验通过%n", startVal);
            System.out.printf("material requests值:%d,校验通过%n", materialVal);
        } else {
            System.out.println("存在小于0的数值,校验不通过");
        }
    }
}

方案2:字符串分割(适合格式完全固定的场景)

public class LogFieldParser {
    public static void main(String[] args) {
        String targetStr = "[start:0 ms, material requests:0 ms, fulfilled requests:329 ms, sum responses:1 ms, total:330 ms]";
        // 去除首尾括号,分割为单个字段项
        String[] fieldItems = targetStr.substring(1, targetStr.length() - 1).split(", ");
        
        int startVal = -1;
        int materialVal = -1;
        
        for (String item : fieldItems) {
            if (item.startsWith("start:")) {
                // 截取数字部分并转换
                startVal = Integer.parseInt(item.split(":")[1].trim().split(" ")[0]);
            } else if (item.startsWith("material requests:")) {
                materialVal = Integer.parseInt(item.split(":")[2].trim().split(" ")[0]);
            }
        }
        
        // 校验逻辑
        if (startVal >= 0 && materialVal >= 0) {
            System.out.printf("start值:%d,校验通过%n", startVal);
            System.out.printf("material requests值:%d,校验通过%n", materialVal);
        } else {
            System.out.println("数值不符合要求,存在小于0的情况");
        }
    }
}

额外说明

  • 如果日志中数值可能为小数,需将正则中的\\d+改为\\d+(\\.\\d+)?,并将变量类型改为double
  • 实际使用时建议添加异常捕获,处理字段不存在、数值格式错误等情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:40:36