Java 正则表达式分别去除字符串左侧、右侧的0

部分字符串左侧或右侧会补零以此达到某种效果,如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
    }
}


发布了32 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/piaoranyuji/article/details/90693009
今日推荐