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

在Java中使用replace或extract方法从字符串提取数字并去除数字间空格

Java 从字符串提取数字并移除数字间空格解决方案

场景1:提取所有数字直接拼接

直接使用replaceAll一次性移除所有非数字字符即可:

String input = "its 2 3 4  5 n and ita 3 5";
String result = input.replaceAll("[^0-9]", "");
// 输出结果:234535

场景2:提取第一组连续空格分隔的数字拼接(匹配你给出的示例输出)

需要先匹配到连续的数字+空格的序列,再移除序列内的空格:

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

public class Test {
    public static void main(String[] args) {
        String input = "its 2 3 4  5 n and ita 3 5";
        // 匹配由空格分隔的数字序列,兼容单个数字场景
        Pattern pattern = Pattern.compile("\\d+(?:\\s+\\d+)*");
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            String result = matcher.group().replaceAll("\\s", "");
            System.out.println(result);
            // 输出结果:2345
        }
    }
}

拓展说明

  • 如果需要提取所有独立的数字序列,循环调用matcher.find()遍历所有匹配结果即可
  • 如果需要自定义数字序列的分隔规则,调整正则表达式中Pattern的匹配规则即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 21:36:01