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

如何用Java的Pattern和Matcher提取卡牌ID与数值列表

使用Pattern和Matcher提取Card数据

你的核心问题是:Java中重复捕获的分组只会保留最后一次匹配结果,所以原正则无法直接收集所有数值。下面给出两种可行的实现方案:

方案一:分两步匹配(清晰直观)

先提取ID,再单独匹配冒号后的所有数值:

String input = "Card 1: 32 45 88  1";

// 提取卡片ID
Matcher idMatcher = Pattern.compile("Card\\s+(\\d+):").matcher(input);
Integer id = idMatcher.find() ? Integer.parseInt(idMatcher.group(1)) : null;

// 提取所有数值(从ID匹配结束的位置开始,跳过ID本身的数字)
Matcher valueMatcher = Pattern.compile("\\d+").matcher(input);
List<Integer> values = new ArrayList<>();
while (valueMatcher.find(idMatcher.end())) {
    values.add(Integer.parseInt(valueMatcher.group()));
}

// 组装Card对象
Card card = new Card();
card.setId(id);
card.setValues(values);

方案二:单正则遍历(更紧凑)

用一个正则同时匹配ID和数值,通过分组判断类型:

String input = "Card 1: 32 45 88  1";
Pattern pattern = Pattern.compile("Card\\s+(\\d+):|(\\d+)");
Matcher matcher = pattern.matcher(input);

Integer id = null;
List<Integer> values = new ArrayList<>();

while (matcher.find()) {
    // 匹配到ID分组
    if (matcher.group(1) != null) {
        id = Integer.parseInt(matcher.group(1));
    }
    // 匹配到数值分组
    else if (matcher.group(2) != null) {
        values.add(Integer.parseInt(matcher.group(2)));
    }
}

关键细节

  • 原正则Card\\s+(\\d+):(\\s+(\\d+))+的问题:重复的分组(\\s+(\\d+))只会记录最后一次匹配的数值,无法获取所有值。
  • 数值的格式化空格(%2d导致的多空格)不影响\\d+的匹配,因为它仅捕获连续数字序列,忽略前后任意数量的空白。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:55:25