【Java/Regexp】用正则去除数字字符串左边多余的零

代码:

package test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 去掉数字字符串左边多余的0
 * @author hy
 *
 */
public class Test7 {
    public static void main(String[] args) {
        String[] arr= {"01","001","0001","0001000","040","097018","0651","50001","10000"};
        
        for(String str:arr) {
            String line=String.format("%-10s%s%10s",str,"=>",trimLeftZero(str));
            System.out.println(line);
        }
    }
    
    /**
     * 去掉数字字符串左边多余的0
     * @param numericText
     * @return
     */
    private static String trimLeftZero(String numericText) {
        Pattern pattern = Pattern.compile("^([0]+)([0-9]*)$", Pattern.CASE_INSENSITIVE);
        
        Matcher matcher=pattern.matcher(numericText);
        while(matcher.find()) {
            return matcher.group(2);
        }
        
        return numericText;
    }
}

输出:

01        =>         1
001       =>         1
0001      =>         1
0001000   =>      1000
040       =>        40
097018    =>     97018
0651      =>       651
50001     =>     50001
10000     =>     10000

END

原文地址:https://www.cnblogs.com/heyang78/p/15746974.html