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

Java如何从字符串中提取出现的第二个数字

提取字符串中第二个连续数字的最优实现方案

核心思路

通过正则匹配捕获字符串中所有连续的数字序列,直接取第二个匹配结果即可,该方案不依赖数字前后的固定文本格式,适配所有动态变化的符合规则的输入字符串。

主流语言实现示例

Java 实现(适配你给出的示例代码场景)

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

public class GetSecondNumber {
    public static void main(String[] args) {
        String a = "I have 102 string but 123453 is best";
        Pattern numPattern = Pattern.compile("\\d+");
        Matcher matcher = numPattern.matcher(a);
        String targetNum = "";
        int matchCount = 0;
        while (matcher.find()) {
            // 第二次匹配到的数字就是目标值
            if (matchCount == 1) {
                targetNum = matcher.group();
                break;
            }
            matchCount++;
        }
        // 输出结果为 123453
        System.out.println(targetNum);
    }
}

Python 实现

import re

input_str = "I have 102 string but 123453 is best"
# 提取所有连续数字序列
all_nums = re.findall(r'\d+', input_str)
# 索引从0开始,第2个数字对应索引1
target_num = all_nums[1] if len(all_nums) >= 2 else ""
print(target_num)

方案优势

  • 鲁棒性强:不依赖数字周边的文本格式,不管非数字部分是中文、英文、符号、空格都能正确匹配
  • 性能优秀:单次遍历字符串即可完成所有数字匹配,时间复杂度为O(n)(n为字符串长度)
  • 扩展性好:如果后续需要调整为提取第N个数字,仅需要修改对应匹配计数或索引值即可

注意事项

实际使用时建议增加数字数量不足的异常判断,避免出现索引越界、空值等问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:15:02