Java pads numbers in strings with zeros using regular rules

Sometimes you encounter this situation when sorting strings:

Water Margin Episode 1.mp4

Water Margin Episode 2.mp4

Water Margin Episode 10.mp4

Water Margin Episode 11.mp4

When sorting, "Water Margin Episode 10.mp4" will be ranked before "Water Margin Episode 2.mp4", and the sorted result becomes:

Water Margin Episode 1.mp4

Water Margin Episode 10.mp4

Water Margin Episode 11.mp4

Water Margin Episode 2.mp4

solution

You can first add 0 to the numbers in the string through regular expression, and then remove the excess 0 through regular expression.

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

Processed result:

Water Margin Episode 011.mp4

おすすめ

転載: blog.csdn.net/watson2017/article/details/132227498