将字符串转换为自定义标准格式

时间:2018-07-31 19:15:47

标签: java spring spring-boot spring-data-jpa

我试图将下面的示例字符串转换为不同的格式-

String s="MH1BM4";(sample string)
String s="MHA1BM4";(sample string)

String s="MH-01-CM-0004";(o/p)

String s="MH-01-CM-0034";(o/p)

String s="MGH-01-CM-03334";(o/p)

String s="MH-01-CM-03334";(o/p)
如果出现个位数,则排第二位,我需要附加-0并输入 如果少于4位,则排在第四位。我需要相应地加上-0。

反正有使用regx进行转换吗?

1 个答案:

答案 0 :(得分:1)

考虑使用String.format()将数字转换为“正确”格式。例如,

.table-sm

输出:0004

有关此处的格式的更多信息:https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

还有一些示例:https://www.dotnetperls.com/format-java

相关问题