对文本之间的数字进行格式化的最简单方法是什么?



格式化文本之间的数字的最简单方法是什么?

String s1 = "1128 ... 9812"; //What I have
"1,128 ... 9,812" //Expected result
String s2 = "823446 ... 26 ... 239173"; //What I have
"823,446 ... 26 ... 239,173" //Expected result
String s3 = "8012332 ... 7283912011"; //What I have
"8,012,332 ... 7,283,912,011" //Expected result

没有一行代码可以完成这个任务,但是如果你需要重复执行这个任务,你可以声明一个方法/函数/UnaryOperator并重用它。(假设你所有的数字都适合一个长)

public static void main(String[] args) {
NumberFormat nf = new DecimalFormat("###,###");
UnaryOperator<String> function = s -> {
Pattern p = Pattern.compile("\d{4,}");
Matcher m = p.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, nf.format(Long.parseLong(m.group())));
}
m.appendTail(sb);
return sb.toString();
};
String s1 = "1128 ... 9812"; //What I have        "1,128 ... 9,812" //Expected result
String s2 = "823446 ... 26 ... 239173"; //What I have        "823,446 ... 26 ... 239,173" //Expected result
String s3 = "8012332 ... 7283912011"; //What I have        "8,012,332 ... 7,283,912,011" //Expected result
s1 = function.apply(s1);
s2 = function.apply(s2);
s3 = function.apply(s3);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}

最新更新