部分字符串左侧或右侧会补零以此达到某种效果,如10位定长字符串 “0000001230” 和 “1234500000”,项目中有时需要去除左侧和右侧的0,只保留一侧非零字符串,可通过正则表达式去除0值,代码如下。
package com.test;
/**
* @description
* @date 2019/5/30 10:26
*/
public class Test1 {
public static void main(String[] args) {
// 去除字符串左侧的0值
String str = "0000001230";
String str1 = str.replaceAll("^(0+)", "");
System.out.println(str1); // 1230
// 去除字符串右侧的0值
String str2 = "1234500000";
String str3 = str2.replaceAll("0*$", "");
System.out.println(str3); // 12345
}
}