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

如何用单行字符串格式化给版本号补前导零(禁用拆分类方法)

解决方案

可以利用正则表达式的替换功能,配合String.format实现单行格式化,完全不需要使用字符串拆分类方法:

// 针对Java 9及以上版本
System.out.println("8.1.8".replaceAll("\\d+", match -> String.format("%02d", Integer.parseInt(match.group()))));

原理说明

  • \\d+正则表达式会匹配字符串中所有连续的数字片段
  • replaceAll的函数式参数会对每个匹配到的数字片段做处理:将其转为整数后用%02d格式化为两位数字(不足补零)
  • 执行后,8.1.8会被替换为08.01.08,8.1.14会被替换为08.01.14,完全符合需求

兼容Java 8的单行写法

如果需要兼容Java 8(不支持函数式参数的replaceAll),可以用Pattern和Matcher组合实现单行:

System.out.println(java.util.regex.Pattern.compile("\\d+").matcher("8.1.8").replaceAll(r -> String.format("%02d", Integer.parseInt(r.group()))));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:55:10