Java通过正则对字符串中的数字补零

在字符串排序时有时会遇到这种情况:

水浒传 第1集.mp4

水浒传 第2集.mp4

水浒传 第10集.mp4

水浒传 第11集.mp4

排序时,“水浒传 第10集.mp4”会排在“水浒传 第2集.mp4”前面,排序后的结果变成:

水浒传 第1集.mp4

水浒传 第10集.mp4

水浒传 第11集.mp4

水浒传 第2集.mp4

解决方案

可以先通过正则对字符串中的数字补0,然后再通过正则去除掉多余的0

String text = "水浒传 第11集.mp4";
text = text.replaceAll("(\\d+)", "00$1");
text = text.replaceAll("0*([0-9]{3})", "$1");
System.out.println(text);

处理后的结果:

水浒传 第011集.mp4

猜你喜欢

转载自blog.csdn.net/watson2017/article/details/132227498
今日推荐